首页 > 解决方案 > with file.open('r',encoding="utf-8") as f: AttributeError: 'str' object has no attribute 'open'

问题描述

我正在尝试从一些 xml 文件中提取数据,我有几个目录,每个目录中都有很多文件。这些文件具有相同的名称,但每个文件夹中的数据不同。

例如:文件夹>>英文有文件名为new.xml文件夹>>阿拉伯语有文件名为new.xml

我需要破解新的并从中获取一些数据。我收到此错误。

这是我的代码,我做错了什么?

import pathlib
import lxml.etree as etree
from lxml.builder import ElementMaker
import functools
import operator

# Extract the name
cwd = pathlib.Path.cwd()
dirs = list(filter(lambda d: d.is_dir(), cwd.iterdir()))
langs = [dir_.name for dir_ in dirs]
files = map(operator.methodcaller('glob', '*.xml'), dirs)
files = map(lambda d: list(map(lambda f: f.with_suffix('').with_suffix('').name, d)), files)
filenames = set(functools.reduce(operator.add, files))

#print(langs)
#print(filenames)

# I will add the names of the files to the identifiers
identifiers = dict()

for file in filenames:
    with file.open('r',encoding="utf-8") as f:
        tree = etree.parse(file)
    root = tree.getroot()
    identifiers[filename] = root
    print(list(root.tag))

标签: pythonpython-3.xxmlautomationpython-requests

解决方案


在您的示例中,变量文件具有字符串类型。该错误表明您正在尝试对字符串对象调用 open 函数。您需要使用以下代码。

with open(file, 'r', encoding='UTF-8') as f:

推荐阅读