如何使用python按特定顺序对文件名进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37796598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort file names in a particular order using python
提问by Lou
Is there a simple way to sort files in a directory in python? The files I have in mind come in an ordering as
有没有一种简单的方法可以在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
What I want is something like
我想要的是类似的东西
file_01_001
file_02_002
file_03_003
file_04_004
file_01_005
file_02_006
...
I am currently opening them using glob
for the directory as follows:
我目前正在使用glob
目录打开它们,如下所示:
for filename in glob(path):
with open(filename,'rb') as thefile:
#Do stuff to each file
So, while the program performs the desired tasks, it's giving incorrect data if I do more than one file at a time, due to the ordering of the files. Any ideas?
因此,当程序执行所需的任务时,如果我一次执行多个文件,由于文件的顺序,它会提供不正确的数据。有任何想法吗?
回答by Gene Burinsky
As mentioned, files in a directory are not inherently sorted in a particular way. Thus, we usually 1) grab the file names 2) sort the file names by desired property 3) process the files in the sorted order.
如前所述,目录中的文件本身并不是以特定方式排序的。因此,我们通常 1) 获取文件名 2) 按所需属性对文件名进行排序 3) 按排序顺序处理文件。
You can get the file names in the directory as follows. Suppose the directory is "~/home" then
您可以按如下方式获取目录中的文件名。假设目录是“~/home”然后
import os
file_list = os.listdir("~/home")
To sort file names:
对文件名进行排序:
#grab last 4 characters of the file name:
def last_4chars(x):
return(x[-4:])
sorted(file_list, key = last_4chars)
So it looks as follows:
所以它看起来如下:
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']
To read in and process them in sorted order, do:
要按排序顺序读入和处理它们,请执行以下操作:
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
回答by Georgios Petasis
A much better solution is to use Tcl's "lsort -dictionary":
更好的解决方案是使用 Tcl 的“lsort -dictionary”:
from tkinter import Tcl
Tcl().call('lsort', '-dict', file_list)
Tcl dictionary sorting will treat numbers correctly, and you will get results similar to the ones a file manager uses for sorting files.
Tcl 字典排序将正确处理数字,您将获得类似于文件管理器用于排序文件的结果。