python读取文件列表并排序
原创
文章标签 python os 程序代码 文件名 文章分类 Python 后端开发
©著作权归作者所有:来自51CTO博客作者CorwinPC的原创作品,请联系作者获取转载授权,否则将追究法律责任
需求:需要按照文件名称顺序进行读取。
目录
这是图片的正确显示顺序:
[En]
This is the correct order in which the pictures are displayed:
一、 修改前的程序代码
#!/usr/bin/python# -*- coding: UTF-8 -*-"""@author: Roc-xb"""import osif __name__ == '__main__': base_dir = "imgs//" file_list = os.listdir(base_dir) for file in file_list: print(file)
二、 修改前的程序的执行结果
显然,读取程序的顺序与我们预期的不同,因此我们可以修改代码。
[En]
Obviously, the order in which the program is read is different from what we expected, so we can modify the code.
三、 修改后的程序代码
#!/usr/bin/python# -*- coding: UTF-8 -*-"""@author: Roc-xb"""import osimport reif __name__ == '__main__': base_dir = "imgs//" file_list = os.listdir(base_dir) file_list.sort(key=lambda x: int(str(re.findall("\d+", x)[0]))) for file in file_list: print(file)
再运行一次,我们就可以得到预期的结果。
[En]
Run it again and we can get the expected results.
四、 修改后的程序执行结果
- 赞
- 收藏
- 评论
- *举报
上一篇:python使用apscheduler库实现定时任务功能
下一篇:No .egg-info directory found in xxx\pip-pip-egg-info-mq
Original: https://blog.51cto.com/u_15629365/5482957
Author: CorwinPC
Title: python读取文件列表并排序
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/513603/
转载文章受原作者版权保护。转载请注明原作者出处!