我想獲取目錄中所有檔案名的串列,但檔案的順序對我很重要。(如果這很重要,我正在使用Google Colab)
PS:我已經接受了第一個答案,但以防萬一知道當我將檔案從谷歌驅動器移動到我的本地 PC 并運行代碼時,它可以正常作業并按照原始順序列印這些檔案。我認為 Google Colab 有問題
假設我的檔案在我的目錄中按以下順序排列:
file1.txt
file2.txt
file3.txt
...
filen.txt
PS:這些檔案名只是為了清楚的例子。實際上,我的檔案名沒有任何要排序的模式,它們就像
1651768933554-b6b4deb3-f245-4763-b38d-71a4b19ca948.wav
當我通過此代碼獲取檔案名時:
import glob
for g in glob.glob(MyPath):
print(g)
我會得到這樣的東西:
file24.txt
file5.txt
file61.txt
...
我想以與檔案夾中相同的順序獲取檔案名。
我盡我所能進行搜索,但沒有找到任何解決我的問題的 SO 帖子。感謝任何幫助。
PS:我也試過from os import listdir
了,還是不行。
uj5u.com熱心網友回復:
它們存在于檔案夾中的方式并不是真正的事情。實際上,他們都坐在記憶中的某個地方,不一定以任何方式彼此相鄰。GUI 通常按字母順序顯示它們,但通常也有過濾器,您可以單擊以按照您選擇的任何方式對它們進行排序。
他們以這種方式列印的原因是因為它是按字母順序排列的。按字母順序2
在之前,5
所以24
在之前5
。
uj5u.com熱心網友回復:
雖然我同意其他評論,但可以選擇使用自然語言排序。這可以通過natsort包來完成。
>>> from natsort import natsorted
>>> files = ['file24.txt', 'file5.txt', 'file61.txt']
>>> sorted_files = natsorted(files)
>>> sorted_files
['file5.txt', 'file24.txt', 'file61.txt']
編輯:
對不起,我之前沒有在包中看到這個。更好地滿足您的需求,請參閱os_sorted
。natsort
>>> from natsort import os_sorted
>>> files = ['file24.txt', 'file5.txt', 'file61.txt']
>>> sorted_files = os_sorted(files)
>>> sorted_files
['file5.txt', 'file24.txt', 'file61.txt']
或者,本質上os.listdir()
...
>>> sorted_directory = os_sorted(os.listdir(directory_path))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/476877.html
標籤:Python python-3.x 文件 小路