按升序对目录中的文件名进行排序 [英] Sort filenames in directory in ascending order
问题描述
我有一个包含 jpg 和其他文件的目录,这些 jpg 都有带有数字的文件名.有些文件名中可能包含其他字符串.
例如.
01.jpg
也可以是
图片03.jpg
在 Python 中,我需要按升序列出所有 jpg 的列表.这是这个的代码片段
导入操作系统将 numpy 导入为 npmyimages = [] #图像文件名列表dirFiles = os.listdir('.') #目录文件列表dirFiles.sort() #良好的初始排序,但在数字上排序不是很好sorted(dirFiles) #按数字升序排序对于 dirFiles 中的文件:#filter out 所有非 jpgs如果文件中有.jpg":myimages.append(文件)打印 len(myimages)打印我的图像
我得到的是这个
['0.jpg', '1.jpg', '10.jpg', '11.jpg', '12.jpg', '13.jpg', '14.jpg',15.jpg"、16.jpg"、17.jpg"、18.jpg"、19.jpg"、2.jpg"、20.jpg"、21.jpg"、22.jpg"、23.jpg"、24.jpg"、25.jpg"、26.jpg"、27.jpg"、28.jpg"、29.jpg"、3.jpg"、30.jpg"、31.jpg"、32.jpg"、33.jpg"、'34.jpg'、'35.jpg'、'36.jpg'、'37.jpg'、'4.jpg'、'5.jpg'、'6.jpg'、'7.jpg'、'8.jpg'、'9.jpg']
显然,它首先对最重要的数字进行盲目排序.我尝试使用 sorted()
正如你所看到的,希望它能修复它,但它没有区别.
假设每个文件名中只有一个数字:
<预><代码>>>>dirFiles = ['图片 03.jpg', '02.jpg', '1.jpg']>>>dirFiles.sort(key=lambda f: int(filter(str.isdigit, f)))>>>目录文件['1.jpg', '02.jpg', '图片03.jpg']同样适用于 Python 3 的版本:
<预><代码>>>>dirFiles.sort(key=lambda f: int(re.sub('D', '', f)))I have a directory with jpgs and other files in it, the jpgs all have filenames with numbers in them. Some may have additional strings in the filename.
For example.
01.jpg
Or it could be
Picture 03.jpg
In Python I need a list of all the jpgs in ascending order. Here is the code snippet for this
import os
import numpy as np
myimages = [] #list of image filenames
dirFiles = os.listdir('.') #list of directory files
dirFiles.sort() #good initial sort but doesnt sort numerically very well
sorted(dirFiles) #sort numerically in ascending order
for files in dirFiles: #filter out all non jpgs
if '.jpg' in files:
myimages.append(files)
print len(myimages)
print myimages
What I get is this
['0.jpg', '1.jpg', '10.jpg', '11.jpg', '12.jpg', '13.jpg', '14.jpg',
'15.jpg', '16.jpg', '17.jpg', '18.jpg', '19.jpg', '2.jpg', '20.jpg',
'21.jpg', '22.jpg', '23.jpg', '24.jpg', '25.jpg', '26.jpg', '27.jpg',
'28.jpg', '29.jpg', '3.jpg', '30.jpg', '31.jpg', '32.jpg', '33.jpg',
'34.jpg', '35.jpg', '36.jpg', '37.jpg', '4.jpg', '5.jpg', '6.jpg',
'7.jpg', '8.jpg', '9.jpg']
Clearly it sorts blindly the most significant number first. I tried using sorted()
as you can see hoping that it would fix it but it makes no difference.
Assuming there's just one number in each file name:
>>> dirFiles = ['Picture 03.jpg', '02.jpg', '1.jpg']
>>> dirFiles.sort(key=lambda f: int(filter(str.isdigit, f)))
>>> dirFiles
['1.jpg', '02.jpg', 'Picture 03.jpg']
A version that also works in Python 3:
>>> dirFiles.sort(key=lambda f: int(re.sub('D', '', f)))
这篇关于按升序对目录中的文件名进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!