python - 如何使用 python 按特定顺序对文件名进行排序

标签 python sorting python-3.x io

有没有一种简单的方法可以在Python中对目录中的文件进行排序?我想到的文件的顺序为

file_01_001
file_01_005
...
file_02_002
file_02_006
...
file_03_003
file_03_007
...
file_04_004
file_04_008

我想要的是这样的

file_01_001
file_02_002
file_03_003
file_04_004
file_01_005
file_02_006
...

我目前正在使用目录的 glob 打开它们,如下所示:

for filename in glob(path):    
    with open(filename,'rb') as thefile:
        #Do stuff to each file

因此,虽然程序执行所需的任务,但如果我一次执行多个文件,由于文件的顺序,它会给出错误的数据。有什么想法吗?

最佳答案

如上所述,目录中的文件本质上并不以特定方式排序。因此,我们通常 1) 获取文件名 2) 按所需属性对文件名进行排序 3) 按排序顺序处理文件。

您可以按如下方式获取目录中的文件名。假设目录是“~/home”那么

import os

file_list = os.listdir("~/home")

对文件名进行排序:

#grab last 4 characters of the file name:
def last_4chars(x):
    return(x[-4:])

sorted(file_list, key = last_4chars)   

所以看起来如下:

In [4]: sorted(file_list, key = last_4chars)
Out[4]:
['file_01_001',
 'file_02_002',
 'file_03_003',
 'file_04_004',
 'file_01_005',
 'file_02_006',
 'file_03_007',
 'file_04_008']

要按排序顺序读入并处理它们,请执行以下操作:

file_list = os.listdir("~/home")

for filename in sorted(file_list, key = last_4chars):    
    with open(filename,'rb') as thefile:
        #Do stuff to each file

关于python - 如何使用 python 按特定顺序对文件名进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37796598/

相关文章:

python - struct.pack 中的 %d 是什么意思?

python-3.x - 如何使用 StringField 验证 Flask 表单中的电话号码?定义最小/最大长度不能限制用户输入文本

python - 在 Python 中清除用户创建的变量

python - numpy OpenBLAS 设置最大线程数

python - 如何正确解码 RTF 中的十六进制值

python - FTP 上传文件手动工作,但使用 Python ftplib 失败

javascript - 为什么数字数组,更多数据排序比对象数组更快,Javascript中的数据更少?

arrays - 数字流中第 K 小的

javascript - 我如何按 ABC 对名称的 javascript.map 数组进行排序

python-3.x - 使用 ctypes 将带有省略号样式的 varargs 的 c 函数转换为等效的 python