首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在python中使用replace()函数时出现无效起始字节错误

在python中使用replace()函数时出现无效起始字节错误
EN

Stack Overflow用户
提问于 2018-08-22 07:25:36
回答 1查看 238关注 0票数 0

我正在运行一段简单的代码,将文件中的一个单词替换为另一个单词,如下所示:

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

我不确定这是什么意思,或者这里的错误是什么?我在过去多次运行这个脚本,没有任何问题。任何关于解决这个问题的帮助都是很棒的!

EN

回答 1

Stack Overflow用户

发布于 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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51957971

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档