[英]How do I identify all .txt files in a directory and subdirectories in Python?
I am trying to loop through all.txt files in a file directory that contains a bunch of subdirectories.我正在尝试遍历包含一堆子目录的文件目录中的 all.txt 文件。 The.txt files are in the subdirectories.
.txt 文件位于子目录中。 Here is what I have in a.py so far:
到目前为止,这是我在 a.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"
The issue with this is that I don't have.txt files in the directory, so I need to put the above Python file in the subdirectory with the text files for the above code to work.问题是我的目录中没有.txt 文件,所以我需要将上面的 Python 文件放在带有文本文件的子目录中,上面的代码才能工作。 I want to be able to loop from the directory and go through every subdirectory.
我希望能够从目录和 go 循环通过每个子目录。 Any suggestions are welcome.
欢迎任何建议。
This worked:这有效:
import os
import csv
import re
import glob
csv_cont = []
for file in glob.glob('**/*.txt', recursive=True):
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.