我正在运行一段简单的代码,将文件中的一个单词替换为另一个单词,如下所示:
import random
import os
path = '/path/of/file/'
files = os.listdir (path)
for file in files:
with open (path + file) as f:
newText = f.read().replace('Plastic Ba','PlasticBag')
with open (path + file, "w") as f:
f.write(newText)
在这样做的过程中,我得到了一个以前从未遇到过的错误:
Traceback (most recent call last):
File "replaceText.py", line 9, in <module>
newText = f.read().replace('Plastic Ba', 'PlasticBag')
File "/Users/vivek/anaconda3/lib/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 3131: invalid start byte
我不确定这是什么意思,或者这里的错误是什么?我在过去多次运行这个脚本,没有任何问题。任何关于解决这个问题的帮助都是很棒的!
发布于 2018-08-22 08:01:13
你有没有试着把文件编码成'UTF-8‘?请检查Open函数参数,
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
在脚本中,尝试使用,
with open (path + file, 'r', encoding='windows-1252') as f:
您还可以查看编解码器库中提供的open方法。请检查此问题。Unicode (UTF-8) reading and writing to files in Python
UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte
https://stackoverflow.com/questions/51957971
复制相似问题