繁体   English   中英

仅使用python查找子目录中的文件

[英]find files in subdirectories only with python

我有一个带有子文件夹( CF1CF2CF3 ...)的父文件夹( PF ),并且在父文件夹( PFf1.csvPFf2.csv ,...)和子文件夹( CF1f1.csvCF1f2.csv文件CF1f2.csvCF2f1.csvCF2f2.csv ,...)

我只想在子文件夹( CF1f1.csvCF1f2.csvCF2f1.csvCF2f2.csv ,...)中找到文件,而忽略父文件夹中的文件。

我在stackoverflow和Internet中看到的所有示例都具有以下形式:

for folder, subfolders, files in os.walk(rootDir):
   for f in files:
      print(f)

它也可以在父文件夹中找到文件。 我尝试将修改为:

  • 遍历子文件夹

  • 在步行中,测试新的父文件夹何时在子文件夹的原始列表中,然后分支到if语句中

但没有成功。 我觉得这应该很容易,但是我是python新手,无法弄清楚。 任何帮助将非常感激。

您的循环为您提供了当前文件夹的路径,您可以检查它是否与rootDir不同(提供的rootDirrootDir的完整路径):

for folder, subfolders, files in os.walk(rootDir):
    if folder != rootDir:
        for f in files:
            print(f)

如果您想要的只是给定目录中目录中的文件,那么Walk太多了。 为此,我会写:

for name in os.listdir(base):
    if os.path.isdir(os.path.join(base, name)):
       for file in os.listdir(os.path.join(base, name)):
           if os.path.isfile(os.path.join(base, name, file)):
               print(os.path.join(base, name, file))

当然,有一些冗余的os.path.join

您可以首先使用os.listdir获取根目录中的所有子目录,并使用os.path.isdir进行检查:

>>> from os import listdir
>>> from os.path import isfile, isdir, join

>>> root_dir = './PF'
>>> sub_dirs = [join(root_dir, dir) for dir in listdir(root_dir) if isdir(join(root_dir, dir))]
>>> sub_dirs
['./PF/CF2', './PF/CF1']

然后使用os.listdir再次遍历所有子目录以获取其中的文件。 您可以使用os.path.isfile仅检查文件:

>>> sub_dir_files = [f for subdir in sub_dirs for f in listdir(subdir) if isfile(join(subdir, f))]
>>> sub_dir_files
['CF2f2.txt', 'CF2f1.txt', 'CF1f2.txt', 'CF1f1.txt']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM