python - 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))
解决方案
在您的示例中,变量文件具有字符串类型。该错误表明您正在尝试对字符串对象调用 open 函数。您需要使用以下代码。
with open(file, 'r', encoding='UTF-8') as f:
推荐阅读
- php - 如何打开/激活 php 5.4 的 openssl exention?
- python - 有没有办法在 python 中读取标准输出?
- python - Python 函数适用于标量,但不适用于向量,并给我错误“只有 size-1 数组可以转换为 Python 标量”
- tensorflow - tensorflow,从参差不齐的张量中删除空元素
- java - 骆驼停放的线程
- node.js - 猫鼬如何知道我正在访问什么集合?
- javascript - 使用符号链接在多个 React 应用程序之间共享代码
- mysql - mySQL 在一个表上失去连接,在任何其他表上都没有
- python - Scrapy css 选择器返回一个空的价目表
- sql - 如何在 SQL 案例研究中按每个级别级别聚合?