从 python 中的特定文件夹获取文件

Get files from specific folders in python

我的目录结构如下:

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)
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)

您可以使用 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)