【问题标题】:How do I identify all .txt files in a directory and subdirectories in Python?如何在 Python 中识别目录和子目录中的所有 .txt 文件?
【发布时间】: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


【解决方案1】:

这行得通:

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"

【讨论】:

    猜你喜欢
    • 2018-01-13
    • 2014-11-10
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 2012-11-14
    相关资源
    最近更新 更多