python - 将字节写入文件,编码错误

标签 python encoding python-3.x

我在 Python 3.x 中写入文件时遇到问题,FOR 中的 write 函数正在以 utf-8 编码写入捷克符号。 我是 Python 新手,但我为“utf-8”编码设置了 IDE 和 .py、.xml 文件,我不知道为什么输出文件看起来像这样。 我的代码:

-*- coding: utf-8 -*-
from lxml import etree
from io import BytesIO
import sys
import codecs

f = open('uzivatelska_prirucka.xml','rb')
fo = open('try.xml','wb',1)

header = '?xml version="1.0" encoding="utf-8"?>\n<root\n'
fo.write(bytes(header,'UTF-8'))

some_file_like_object = f
tree = etree.parse(some_file_like_object)
root = tree.getroot() 
node = tree.xpath('/prirucka/body/p');

for a in node:
    for b in a.getiterator():
        if not (b.find('r') is None): 
            text = etree.tostring(b.find('r'))
            fo.write(bytes(str(text),'UTF-8'))

感谢您的帮助和建议

最佳答案

是否需要以二进制方式读写?
我认为 XML 文件是一个简单的文本文件,您可以像 txt 文件一样使用它
你还应该知道 python3.2 和较新版本的 python 在 ASCII 和 UTF 字符串之间没有任何区别
python3.2及以上版本将所有字符串视为unicode字符串,因此无论字符串是否包含非ASCII字符,您都可以在输出文件中写入字符串
此外,我发现不需要以二进制模式打开文件即可与 lxml.etree

一起使用

尝试以文本模式打开文件(在打开模式下去掉 b )并查看它是否有效,但请记住告诉 open 使用 utf-8打开文件的编码

f = open('uzivatelska_prirucka.xml', 'r', encoding='utf-8')
fo = open('try.xml', 'w', 1, encoding='utf-8')

作为旁注,您可以这样写:

if b.find('r'):  

而不是:

if not (b.find('r') is None):  

因为 if 子句中的 None 假定为 False 并且 if find() 返回 None python 本身不这样做t 运行 if block 中的代码并跳转:

$ python3.3
Python 3.3.1 (default, Apr 17 2013, 22:30:32) 
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print(1) if None else print(0)
0
>>> print(1) if not None else print(0)
1

祝你编码愉快;)

关于python - 将字节写入文件,编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18567640/

相关文章:

php - 如何打印latin1数据库中的UTF-8数据?

video - 用于移动设备的 ffmpeg 视频编码

python - UTF-8 编码异常与 subprocess.run

python - 用 np.NaN 替换 pandas 数据框中的缺失值(以字符串形式给出)

python-3.x - 这个函数声明中 -> List[int] 是什么意思?

python - selenium.common.exceptions.WebDriverException : Message: 'firefox' executable needs to be in PATH with GeckoDriver Firefox Selenium and Python

python - while 循环用户输入?

python脚本读取文本文件并将其解析为csv格式

python - 在事件流之外运行 asyncio 协程

python - 在 Python 中使用 .find 查找第一个非数字字符