【发布时间】:2021-07-01 08:13:01
【问题描述】:
python 新手。我正在尝试编写一个代码来遍历给定根文件夹中的子文件夹。在这一点上,我将其视为两个循环。外层循环遍历文件夹,内层循环遍历文件。子文件夹可能有特定的文件。如果找到特定文件或文件夹为空,则内循环将中断,外循环将跳转到下一个文件夹。我有点坚持找出正确的方法来遍历文件夹。如果 os.walk() 是这种情况,我不确定在这种情况下如何使用它:
def folder_surfer():
rootdir = r'C:\Some_folder'
for directory in directories: # Outer loop. Need help with identifying correct method
for file in os.listdir(directory): # Inner loop
if file.endswith('.jdf') or len(os.listdir(directory)) == 0:
break
else:
create_jdf_file('order',directory)
提前致谢!
【问题讨论】:
-
这能回答你的问题吗? Iterating through directories with Python
-
目录未定义,因此不会运行。
-
os.walk(rootdir)是你想要的