python - Python 以数字方式列出文件
问题描述
我有一组文件。
在每个文件中,有一列对应于一个文件编号。它们都以这种格式命名:
test_file_page_#_out_of_7000.txt
例子:
test_file_page_1_out_of_7000.txt
test_file_page_2_out_of_7000.txt
test_file_page_7000_out_of_7000.txt
当我运行以下代码时: output_pages = os.listdir()
这些文件按以下顺序列出:
'test_file_Page_10_out_of_7000.txt', 'test_file_Page_11_out_of_7000.txt', ..., 'test_file_Page_1_out_of_7000.txt', 'test_file_Page_2_out_of_7000.txt'
我想要按此顺序列出的文件:
'test_file_Page_1_out_of_7000.txt', 'test_file_Page_2_out_of_7000.txt', ..., 'test_file_Page_10_out_of_7000.txt', 'test_file_Page_11_out_of_7000.txt'
有什么建议么?
解决方案
该sorted
方法接受一个key
参数,该参数是一个函数,它接受一个列表元素并返回应该用于排序的值:
def get_number(filename):
return int(filename.split("_")[3])
files = sorted(os.listdir(), key=get_number)
推荐阅读
- python - 如何检查作者是否在 x 服务器中具有 x 角色?
- ios - UITapGestureRecognizer 在导航栏 titleView 中的 UIView 上不起作用?
- webpack - AddSpaStaticFiles 'RootPath' 默默地破坏了 webpack devServer 的 HMR
- android - 如何在 android 中使用 gridview 内容创建 PDF?
- flutter - 如何使用 StreamBuilder 将数据设置为 TextEditingController?
- java - 是否拥有相同方法的两个版本,它们的签名(方法名称和“抛出”属性)不同,这被认为是糟糕的设计?
- c++ - 将函数定义作为参数传递时如何理解函数定义
- oracle - 不确定如何从 TOAD 查询 Oracle Apex 19.1 表
- docker - 如何使用 Confluent Schema Registry Docker Image 启用安全性?
- java - 这个通用代码有什么问题(如果没有强制转换(T)就返回失败)