我有几个方法,我做这样的任务。我无法评论解决方案的简洁性。 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))
我知道代码在本质上只是骨骼,但我认为你可以得到的概貌。
后,如果你找到简洁的方式! :)