【发布时间】:2020-10-07 12:31:41
【问题描述】:
我正在尝试编写一个脚本来清除数据 txt 文件中不必要的字符。我能够成功运行一次脚本,但其他所有尝试都会出现错误
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa2 in position 8149: invalid start byte
import codecs
import sys
if len(sys.argv) < 2:
startFile = "test.txt"
else:
startFile = sys.argv[1]
finishFile = "newtest.txt"
def cleanFile():
f = open(startFile, "r")
#f = codecs.open("GNMFDB.TXT", "r", "utf-8")
newFile = open(finishFile, "a")
for line in f:
line = line.replace("=", "")
newFile.write(line)
def clearNewFile():
newFile = open(finishFile, "w")
newFile.close()
if __name__ == "__main__":
#startFile = "test.txt"
#finishFile = "newtest.txt"
clearNewFile()
cleanFile()
我知道这个问题与 UTF-8 试图转换为字符串或类似的东西有关。从原始 .txt 文件中复制一些行并将它们放入我在 vim 中创建的单独 .txt 文件中确实会导致脚本每次都成功运行。我知道编解码器可以用于这样的情况,但是当我尝试它时,它给了我类似的错误(因此该行被注释掉了)。
【问题讨论】:
-
是的,使用编码this
-
您似乎从来没有关闭函数cleanFile中打开的文件,请尝试关闭。