简体   繁体   English

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

[英]Get files from specific folders in python

I have the following directory structure with the following files:我具有以下目录结构,其中包含以下文件:

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

I would like to get only the.txt files from each folder listed.我只想从列出的每个文件夹中获取 .txt 文件。 Example:例子:

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

Note: This entire directory is inside a folder called dataset.注意:整个目录位于名为 dataset 的文件夹中。 My code looks like this, but I believe something is missing.我的代码看起来像这样,但我相信缺少一些东西。 Can someone help me.有人能帮我吗。

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)

Using glob使用glob

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

You can use re module to check that filename ends with .txt .您可以使用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)

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

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