python - 在 python 中订购 os.listdir()

标签 python file

<分区>

如何按顺序将文件添加到列表中

在我的目录中,我有以下文件:slide1.xml、slide2.xml、slide3.xml ... slide13.xml

os.listdir(path) 没有按顺序返回列表

我试过这种方法

files_list = [x for x in sorted(os.listdir(path+"/slides/")) if os.path.isfile(path+"/slides/"+x)]

输出:['slide1.xml', 'slide10.xml', 'slide11.xml', 'slide12.xml', 'slide13.xml', 'slide2.xml', 'slide3.xml' , 'slide3_COPY.xml', 'slide4.xml', 'slide5.xml', 'slide6.xml', 'slide7.xml', 'slide8.xml', 'slide9.xml']

最佳答案

按键排序:

import re
files = ['slide1.xml', 'slide10.xml', 'slide11.xml', 'slide12.xml', 'slide13.xml', 'slide2.xml', 'slide3.xml', 'slide3_COPY.xml', 'slide4.xml', 'slide5.xml', 'slide6.xml', 'slide7.xml', 'slide8.xml', 'slide9.xml']
ordered_files = sorted(files, key=lambda x: (int(re.sub('\D','',x)),x))

给出 ['slide1.xml', 'slide2.xml', 'slide3.xml', 'slide3_COPY.xml', 'slide4.xml', 'slide5.xml', 'slide6.xml', 'slide7.xml'、'slide8.xml'、'slide9.xml'、'slide10.xml'、'slide11.xml'、'slide12.xml'、'slide13.xml']

关于python - 在 python 中订购 os.listdir(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23724653/

相关文章:

python - 使用 PyCapture2 读取 MONO 16 位图像

Python 3.5 connection.py : sock. connect(sa) ConnectionRefusedError: [Errno 111]

file - 删除未使用的 .m 文件

php file_get_contents 阿拉伯字符

java - 如何列出所有大于给定参数的文件?

python - 如何更改seaborn图中的条形宽度?

python - 在 Pygame 1.9.4 中使用 move_ip

file - "./..."是否表示所有子文件夹?

file - 创新设置 : Dynamically add a component for all files in a folder and its subfolders

python 搜索并写入文件