【发布时间】:2021-05-07 04:06:04
【问题描述】:
我正在尝试遍历包含一堆子目录的文件目录中的所有 .txt 文件。 .txt 文件位于子目录中。到目前为止,这是我在 .py 中的内容:
import os
import csv
import re
csv_cont = []
directory = os.getcwd()
for root,dir,files in os.walk(directory):
for file in files:
if file.endswith(".txt"):
f = open(file, 'r')
file_content = f.read()
title = re.search('Title:(.*)', file_content)
if title:
if title.group(1):
title = title.group(1)
else:
title = "\n"
问题在于我的目录中没有 .txt 文件,因此我需要将上面的 Python 文件与文本文件一起放在子目录中,以使上面的代码能够正常工作。我希望能够从目录循环并遍历每个子目录。欢迎提出任何建议。
【问题讨论】:
-
使用
glob模块:glob.glob("parent_dir/**/*.txt", recursive=True)将产生一个字符串列表,其中每个字符串都是一个文本文件的路径。 -
修改行 directory = getcwd() 使目录成为你想要的目录
-
我必须在我的代码中的哪个位置进行更改?我尝试了两种解决方案,但都没有奏效。
标签: python loops file directory