【问题标题】:How to loop throught folders?如何遍历文件夹?
【发布时间】: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)  

提前致谢!

【问题讨论】:

标签: python loops directory


【解决方案1】:

我不确定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)  

【讨论】:

  • 这正是我想要的。谢谢!真的有必要用with吗?
  • @outragebeyond,确实如此。如果由于某种原因在这种情况下您不喜欢上下文管理器,则必须在循环后隐式 .close() fd 和 f 。否则会因为内存泄漏而发出警告。
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 2018-01-16
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
相关资源
最近更新 更多