![](/img/trans.png)
[英]how to sequentially read two txt files and write into a new file in python?
[英]Read txt files sequentially using Python
我按順序讀取txt文件時遇到問題。 我想按以下順序閱讀文件:
0.txt
1.txt
2.txt
...
10.txt
11.txt
...
19.txt
20.txt
21.txt
...
但是,以下代碼
import os
path = "temp/"
dirs = os.listdir(path)
for filename in sorted(dirs):
print filename
回報
0.txt
1.txt
2.txt
10.txt
11.txt
...
19.txt
2.txt
20.txt
...
有什么建議嗎?
您按字面意思對名稱進行排序,而不是可以使用鍵函數來根據名稱的整數值對名稱進行排序:
for filename in sorted(dirs, key=lambda x: int(x.split('.')[0])):
print filename
請注意,如果您的某個文件名不符合正確的格式,則排序可能會引發異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.