簡體   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