简体   繁体   English

Python 以数字方式列出文件

[英]Python Listing Files Numerically

I have a set of files.我有一组文件。

In each file, there is a column that corresponds to a file number.在每个文件中,有一列对应于一个文件编号。 They all are named in this format:它们都以这种格式命名:

test_file_page_#_out_of_7000.txt

Example:例子:

test_file_page_1_out_of_7000.txt
test_file_page_2_out_of_7000.txt
test_file_page_7000_out_of_7000.txt

When I run the following code: output_pages = os.listdir()当我运行以下代码时: output_pages = os.listdir()

The files are listed in this order:这些文件按以下顺序列出:

'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'

I would like the files listed in this order:我想要按此顺序列出的文件:

'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'

Any suggestions?有什么建议么?

The sorted method takes a key argument, which is a function that takes a list element and returns the value that should be used for sorting: sorted方法接受一个key参数,它是一个 function,它接受一个列表元素并返回应该用于排序的值:

def get_number(filename):
    return int(filename.split("_")[3])
    
files = sorted(os.listdir(), key=get_number)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM