[英]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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.