【问题标题】:Get files from specific folders in python从python中的特定文件夹获取文件
【发布时间】:2020-10-31 18:27:44
【问题描述】:

我有以下目录结构,包含以下文件:

Folder_One
├─file1.txt
├─file1.doc
└─file2.txt
Folder_Two
├─file2.txt
├─file2.doc
└─file3.txt

我只想从列出的每个文件夹中获取 .txt 文件。示例:

Folder_One-> file1.txt and file2.txt
Folder_Two-> file2.txt and file3.txt

注意:整个目录位于名为 dataset 的文件夹中。我的代码看起来像这样,但我相信缺少一些东西。谁能帮帮我。

path_dataset = "./dataset/"
filedataset = os.listdir(path_dataset)
    
    for i in filedataset:
        pasta = ''
        pasta = pasta.join(i) 
        for file in glob.glob(path_dataset+"*.txt"):
            print(file)

【问题讨论】:

标签: python file listdir


【解决方案1】:

您可以使用re 模块检查文件名是否以.txt 结尾。

import re
import os
path_dataset = "./dataset/"
l = os.listdir(path_dataset)

for e in l:
   if os.path.isdir("./dataset/" + e):
      ll = os.listdir(path_dataset + e)
      for file in ll:
          if re.match(r".*\.txt$", file):
              print(e + '->' + file)

【讨论】:

    【解决方案2】:
    from pathlib import Path
    
    for path in Path('dataset').rglob('*.txt'):
        print(path.name)
    

    使用glob

    import glob
    for x in glob.glob('dataset/**/*.txt', recursive=True):
        print(x)
    

    【讨论】:

      猜你喜欢
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2016-02-16
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多