目录

# 常规排序sort() 

自然排序natsort

listdir 时间顺序排序:

遍历目录,文件大小倒叙排序

自定义函数排序


# 常规排序sort() 

a = ['1.mp4', '3.mp4', '10.mp4', '2.mp4']
a.sort()
print(a)

可以看到,sort()在进行文件名排序时,是从前往后逐字符比较,这并不是我们想要的结果。这时,可以使用第#三方库natsort。

自然排序natsort

from natsort import natsorted
a = ['1.mp4', '3.mp4', '10.mp4', '2.mp4']
b = natsorted(a)
print(b)

  

倒序:添加参数:reverse=True):

listdir 时间顺序排序:

def get_file_list(file_path):
    dir_list = os.listdir(file_path)
    if not dir_list:
        return
    else:
        # 注意,这里使用lambda表达式,将文件按照最后修改时间顺序升序排列
        # os.path.getmtime() 函数是获取文件最后修改时间
        # os.path.getctime() 函数是获取文件最后创建时间
        dir_list = sorted(dir_list,key=lambda x: os.path.getmtime(os.path.join(file_path, x)))
        # print(dir_list)
        return dir_list

遍历目录,文件大小倒叙排序

import os

def get_file_list(dir_path):

    g = os.walk(dir_path)
    img_files = ['%s/%s' % (i[0], j) for i in g for j in i[-1] if j=='label.csv']

    file_list = sorted(img_files,key=lambda m_file: os.path.getsize(m_file),reverse=True)

    for file in file_list:
        print(int(os.path.getsize(file)/1000),'kb',file)

if __name__ == '__main__':

    get_file_list(dir_path=r"D:\data\similar")

自定义函数排序

import os


DIR = "/home/serho/workspace/lisp"


def compare(x, y):

    stat_x = os.stat(DIR + "/" + x)


    stat_y = os.stat(DIR + "/" + y)


    if stat_x.st_ctime < stat_y.st_ctime:

        return -1

    elif stat_x.st_ctime > stat_y.st_ctime:

        return 1

    else:

        return 0


iterms = os.listdir(DIR)

#Python文件排序
按文件名称字符串小写排序

images.sort(key=lambda x: x.lower())
#按创建时间精确到秒排序

images.sort(key=lambda x: os.path.getctime(x))
#按创建时间,精确到纳秒排序

images.sort(key=lambda x: os.stat(x).st_ctime_ns)
3按文件名称去掉后缀的数值名称排序

images.sort(key = lambda x: int(x[:-4]))
 

#使用os.stat的返回值statinfo的三个属性获取文件的创建时间等信息


statinfo=os.stat("E:\\A\\314_noteach_20190315162753_1552638473_152.png")

st_atime (访问时间), st_mtime (修改时间), st_ctime(创建时间)
print(statinfo)


print(statinfo.st_mtime)
print(statinfo.st_ctime_ns)

#可按照文件名称排序,对字符串和数值混合的可以自定义实现混合排序


# -*- coding: utf-8 -*-
# @Time    : 2019/4/30 13:32
# @Author  : shine
# @File    : mix_sort.py
"""
基于字符串数字混合排序的Python脚本
"""


def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False


def find_continuous_num(astr, c):
    num = ''
    try:
        while not is_number(astr[c]) and c < len(astr):
            c += 1
        while is_number(astr[c]) and c < len(astr):
            num += astr[c]
            c += 1
    except:
        pass
    if num != '':
        return int(num)


def comp2filename(file1, file2):
    smaller_length = min(len(file1), len(file2))
    for c in range(0, smaller_length):
        if not is_number(file1[c]) and not is_number(file2[c]):
            if file1[c] < file2[c]:
                return True
            if file1[c] > file2[c]:
                return False
            if file1[c] == file2[c]:
                if c == smaller_length - 1:
                    if len(file1) < len(file2):
                        return True
                    else:
                        return False
                else:
                    continue
        if is_number(file1[c]) and not is_number(file2[c]):
            return True
        if not is_number(file1[c]) and is_number(file2[c]):
            return False
        if is_number(file1[c]) and is_number(file2[c]):
            if find_continuous_num(file1, c) < find_continuous_num(file2, c):
                return True
            else:
                return False


def sort_list_by_name(lst):
    for i in range(1, len(lst)):
        x = lst[i]
        j = i
        while j > 0 and comp2filename(x, lst[j-1]):
            lst[j] = lst[j-1]
            j -= 1
        lst[j] = x
    return lst

用python对指定目录下的所有文件(夹)大小进行排序
原创goandfly 最后发布于2016-07-29 18:56:45 阅读数 1575  收藏
展开
Windows的某个目录下sort by size只能对该目录下的文件进行排序,不能对目录下的文件夹进行排序,而手工点击右键逐个计算文件夹的大小效比较低。在此我用用python对指定目录下的所有文件(夹)大小进行排序,代码如下:

#! /usr/bin/env python
''' 
Sort the size of floders and files with given directory.
Author: Sean.Xu
'''
import os
import os.path
import datetime

L={}
k={}
rootdir = 'C:\\Windows'

def getdirsize(dir):
    size = 0

    for parent, dirnames, filenames in os.walk(dir):
        for filename in filenames:
            try:
                name = os.path.join(parent, filename)
                size += os.path.getsize(name)
            except:
                continue

    return size

def getsizename(size):
    if (size > 1024*1024*1024.0):
        numstr = str(size/(1024*1024*1024.0))
        sizename = numstr[:(numstr.index('.')+3)]+'GB'
    elif (size > 1024*1024.0):
        numstr = str(size/(1024*1024.0))
        sizename = numstr[:(numstr.index('.')+3)]+'MB'
    elif (size > 1024.0):
        numstr = str(size/1024.0)
        sizename = numstr[:(numstr.index('.')+3)]+'KB'
    else:
        sizename = str(size) +'Bytes'

    return sizename

# proc start
starttime = datetime.datetime.now()

filenames = os.listdir(rootdir)
for filename in filenames:
    fullpath = os.path.join(rootdir, filename)
    if os.path.isdir(fullpath):
        L[filename] = getdirsize(fullpath)
    else:
        L[filename] = os.path.getsize(fullpath)

k = sorted(L.items(), key=lambda L:L[1], reverse = True)
endtime = datetime.datetime.now()

print 'The directory of %s has %d items(folder and file).' %(rootdir, len(k))
print 'It took %ds to sort the size of these items. The result is as below:' %(endtime - starttime).seconds

for i in range(len(k)):
    print k[i][0],"\t",getsizename(k[i][1])

示例中是对C的Windows目录下的文件(夹)进行排序,部分结果如下:

D:\python_example>sortfilesize.py
The directory of C:\Windows has 131 items(folder and file).
It took 68s to sort the size of these items. The result is as below:
Installer       14.30GB
WinSxS  3.92GB
System32        2.35GB
assembly        849.10MB
Microsoft.NET   387.80MB
Fonts   376.48MB
Panther         180.95MB
Symbols         167.64MB
IME     165.17MB
SoftwareDistribution    150.48MB
SystemApps      116.69MB
Speech  110.44MB
INF     73.98MB
Speech_OneCore  50.81MB
servicing       48.02MB
InputMethod     34.57MB
Boot    30.72MB
Performance     28.19MB
Media   26.35MB

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐