简体   繁体   中英

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()

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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