簡體   English   中英

Python 以數字方式列出文件

[英]Python Listing Files Numerically

我有一組文件。

在每個文件中,有一列對應於一個文件編號。 它們都以這種格式命名:

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參數,它是一個 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