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)
提前致谢!
答案 0 :(得分:0)
我不确定 os.walk
是否更适合这里,但如果您确切地知道结构(其中的子文件夹和文件,没有更深层次的递归),以下将起作用。它遍历 rootdir
并检查每个子文件夹是否存在扩展名为 jdf
的文件,如果不存在 - 调用 create_jdf_file
def folder_surfer():
rootdir = r'C:\Some_folder'
with os.scandir(rootdir) as fd:
for folder in fd:
if not folder.is_dir(): continue
with os.scandir(folder) as f:
if not any(file.is_file() and file.name.endswith('.jdf') for file in f):
create_jdf_file('order', folder.name)