我有幾個方法,我做這樣的任務。我無法評論解決方案的簡潔性。 FWIW在這裏他們是:
1.下面的代碼將採取所有以.txt結尾的文件。你可能想在這裏去掉「.endswith」部分
import os
for root, dirs, files in os.walk('./'): #current directory in terminal
for file in files:
if file.endswith('.txt'):
#here you can do whatever you want to with the file.
2,本代碼將假設路徑提供的功能和將所有.txt文件添加到列表中,如果有子目錄中路徑,它將追加子目錄下的那些文件到子文件
def readFilesNameList(self, path):
basePath = path
allfiles = []
subfiles = []
for root, dirs, files in os.walk(basePath):
for f in files:
if f.endswith('.txt'):
allfiles.append(os.path.join(root,f))
if root!=basePath:
subfiles.append(os.path.join(root, f))
我知道代碼在本質上只是骨骼,但我認爲你可以得到的概貌。
後,如果你找到簡潔的方式! :)