我正在尝试创建Folder_A文件列表,Folder_B一直到Folder_Z然后执行操作"执行此操作"。我想将每个文件夹中的所有文件添加到一个列表,file_list,预先执行操作"执行此操作"然后将列表重置为空并转到下一个文件夹。
Run Code:
Folder_A files to folder_list, preform "do this"
empty folder_list
Folder_B files to folder_list, preform "do this"
empty folder_list
...
Folder_Z files to folder_list, preform "do this"
empty folder_list
我该怎么做?这是我目前的代码:
folder_list = []
for dirName, subdirList, fileList in os.walk(Path):
for filename in fileList:
if "_Folder" in dirName:
if ".txt" in filename.lower():
folder_list.append(os.path.join(dirName,filename))
"do this"
此代码将所有文件从每个文件夹添加到列表中,因此如果Folder_A到Folder_Z每个包含3个文件,则我的列表将填充到78个文件,然后执行操作"执行此操作"而不是做前3,重置,然后前进。
答案 0 :(得分:2)
每次folder_list
为folder_list = []
时,您都会将if ".txt" in filename.lower():
重新定义为True
。
folder_list = []
for dirName, subdirList, fileList in os.walk(Path):
for filename in fileList:
if "_Folder" in dirName:
if ".txt" in filename.lower():
folder_list.append(os.path.join(dirName,filename))
"do this"