【问题标题】:Load, Open and Operate with RegEx, text files in Python使用正则表达式加载、打开和操作 Python 中的文本文件
【发布时间】:2019-01-01 06:34:35
【问题描述】:
import re
import os

def scan_folder(parent):
    # iterate over all the files in directory 'parent'
    for file_name in os.listdir(parent):
        if file_name.endswith(".txt"):
            mensaje = file_name.read()
            mensaje = mensaje.replace("\n","")

            # Number of CVE from "DiarioOficial"
            regex = r"\s*CVE\s+([^|]*)"
            matches = re.search(regex, mensaje)
            if matches:
                print (matches.group(1).strip())
scan_folder("/Users/.../DiarioOficial")

我有之前的代码来加载和打开位于这条路线的所有 .txt。我想执行这个路由中所有txt文件实现的正则表达式的功能。

它不起作用,它给了我:

Traceback (most recent call last):
  File "/Users/anna/PycharmProjects/extractData/Principal.py", line 80, in <module>
    scan_folder("/Users/anna/PycharmProjects/extractData/DiarioOficial")
  File "/Users/anna/PycharmProjects/extractData/Principal.py", line 16, in scan_folder
    mensaje = file_name.read()
AttributeError: 'str' object has no attribute 'read'

我想浏览所有文件并在每个文件中进行相同的操作。

【问题讨论】:

标签: python regex file path directory


【解决方案1】:

你应该替换:

mensaje = file_name.read()

与:

mensaje = open(file_name).read()

【讨论】:

    【解决方案2】:

    您缺少一个公开声明。 file_name 是一个字符串对象,它只是文件的名称。要首先打开文件,您必须调用 open。最方便的是像这样使用 with open ,因为它省去了您手动关闭文件的麻烦:

    with open(file_name) as f:
        mensaja = f.read()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      相关资源
      最近更新 更多