3 回答

TA贡献1820条经验 获得超10个赞
你应该尝试使用os.walk
yourpath = 'path'
import os
for root, dirs, files in os.walk(yourpath, topdown=False):
for name in files:
print(os.path.join(root, name))
stuff
for name in dirs:
print(os.path.join(root, name))
stuff

TA贡献1858条经验 获得超8个赞
实际上,您可以只使用os模块来完成这两项:
列出文件夹中的所有文件
按文件类型,文件名等对文件进行排序
这是一个简单的例子:
import os #os module imported here
location = os.getcwd() # get present working directory location here
counter = 0 #keep a count of all files found
csvfiles = [] #list to store all csv files found at location
filebeginwithhello = [] # list to keep all files that begin with 'hello'
otherfiles = [] #list to keep any other file that do not match the criteria
for file in os.listdir(location):
try:
if file.endswith(".csv"):
print "csv file found:\t", file
csvfiles.append(str(file))
counter = counter+1
elif file.startswith("hello") and file.endswith(".csv"): #because some files may start with hello and also be a csv file
print "csv file found:\t", file
csvfiles.append(str(file))
counter = counter+1
elif file.startswith("hello"):
print "hello files found: \t", file
filebeginwithhello.append(file)
counter = counter+1
else:
otherfiles.append(file)
counter = counter+1
except Exception as e:
raise e
print "No files found here!"
print "Total files found:\t", counter
现在,您不仅列出了文件夹中的所有文件,而且(可选)按起始名称,文件类型等对它们进行了排序。刚才遍历每个列表并做您的工作。
添加回答
举报