python - 在 Python 中将数据写入文件会出现与 UNICODE 相关的错误

标签 python file-io

我基本上是使用 Python 中的 SAX 解析器解析 XML 中的数据。

我能够解析和打印。但是我想将数据放入文本文件中。

示例:

def startElement(self, name, attrs):
    file.write("startElement'"+ name + " ' ")

尝试使用上述示例代码将一些文本写入 test.txt 时,出现以下错误:

TypeError: descriptor 'write' requires a 'file' object but received a 'unicode'

非常感谢任何帮助。

最佳答案

您没有使用打开的文件。您正在使用file type 。然后,file.write 方法被取消绑定(bind),它期望绑定(bind)一个打开的文件:

>>> file
<type 'file'>
>>> file.write
<method 'write' of 'file' objects>
>>> file.write(u'Hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'write' requires a 'file' object but received a 'unicode'

如果你有一个已经打开的文件对象,那么使用它;也许您在 self 上有一个名为 file属性:

self.file.write("startElement'" + name + " ' ")

但请考虑到,因为 name 是一个 Unicode 值,您可能希望将信息编码为字节:

self.file.write("startElement'" + name.encode('utf8') + " ' ")

您还可以使用 io.open() function创建一个文件对象,该对象将接受 Unicode 值并在写入时将这些值编码为给定的编码:

file_object = io.open(filename, 'w', encoding='utf8')

但是您需要明确始终写入 Unicode 值,而不是混合字节字符串(类型 str)和 Unicode 字符串(类型 unicode)。

关于python - 在 Python 中将数据写入文件会出现与 UNICODE 相关的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28041813/

相关文章:

python - 如何判断函数来自哪个模块?

python - E : Package 'python-pip' has no installation candidate

bash - 我可以编写一个程序以使用文本文件中的参数重复运行吗?

python - 批量重命名目录中的文件

c++ - 将 float 读入一个动态分配的数组,同时在读取文件时增加数组的大小

具有上下文管理器和属性的 Python 多处理管理器

Python3(Urllib) -<绑定(bind)方法 HTTPResponse.read of <http.client.HTTPResponse object at 0x03281BD0>>

android - 在 USB 主机模式下安装的 USB 存储设备上的文件 I/O(Android 3.1 及更高版本)

C:将文本文件中的值保存到内存字段

python - 当 glob 以斜杠结尾时,如何防止 pathlib 的 Path.glob 返回文件?