我基本上是使用 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/