3 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
你應(yīng)該嘗試使用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貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊
實(shí)際上,您可以只使用os模塊來完成這兩項(xiàng):
列出文件夾中的所有文件
按文件類型,文件名等對文件進(jìn)行排序
這是一個(gè)簡單的例子:
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
現(xiàn)在,您不僅列出了文件夾中的所有文件,而且(可選)按起始名稱,文件類型等對它們進(jìn)行了排序。剛才遍歷每個(gè)列表并做您的工作。
添加回答
舉報(bào)