python - 通过 Python 3 修改非文本文件

标签 python image python-3.x utf-8 utf8-decode

我正在开发一个加密/解密程序,我让它可以处理文本文件;但是,我无法打开任何其他格式。例如,如果我这样做:

a_file = open('C:\Images\image.png', 'r', encoding='utf-8')
for a_line in a_file:
    print(a_line)

我得到:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Comp_Sci/Coding/line_read_test.py", line 2, in <module>
for a_line in a_file:
File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\codecs.py", line 319, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

我做错了什么?

最佳答案

简短版本:您正在以文本模式打开二进制文件。使用 'rb' 而不是 'r'(并删除 encoding 参数),你会做对的。

长版本:Python 3 对bytestringsUnicode strings 进行了非常严格的区分。 str 类型包含 Unicode 字符串; str 的每个字符都是一个 Unicode 代码点。另一方面,bytes 类型表示一系列不一定对应于文本的 8 位值。例如,.PNG 文件应该作为 bytes 对象加载,而不是作为 str 对象加载。通过将 encoding="utf-8" 参数传递给 open(),您告诉 Python 您的文件只包含有效的 UTF-8 文本,它是一个 .PNG显然没有。相反,您应该使用 'rb' 将文件作为二进制文件打开,而不是使用任何编码。然后,当您读取文件时,您将获得 bytes 对象而不是 str 对象,您需要区别对待它们。

我看到 @ignacio-vazquez-abrams 在我输入这个答案时已经发布了很好的示例代码,所以我不会重复他的工作。他的代码是正确的:使用它,你会没事的。

关于python - 通过 Python 3 修改非文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33075058/

相关文章:

Python-串行读取并使用正则表达式对数据进行分组

html - 为什么 Safari 有时只渲染图像的顶部?

python - 调用不同的函数 tkinter

python - 验证错误 : Redefined outer name from outer scope

Python线程发布

python - 迭代 Django 表单结果(不在模板中)

Python 基于属性的有序列表

css - 仅在文本链接悬停 CSS 时显示图像

linux - 有没有办法在终端中打印图像直方图统计信息?

python - 在另一台计算机上运行 pyinstaller .exe 文件时缺少 .dll