遍历文件夹中的所有txt文件时出现Unicode解码错误

时间:2019-05-22 15:55:55

标签: python python-3.x

我想将表达式| SYS写入文件夹中的每个txt文件中。但是我收到Unicode解码错误。我怀疑这可能是因为字符串r

中缺少with open(txt_file, "r") as f:

我的代码是:

import os
import csv
import glob

cwd = os.getcwd()

directory = cwd

output = cwd

txt_files = os.path.join(directory, '*.txt')

for txt_file in glob.glob(txt_files):
    with open(txt_file, "r") as f:
        a = f.read()
        print(a)
#Now writing into the file with the prepend line + old file data
    with open(txt_file, "w") as f:
        f.write("|   SYS" + a)
        #below code to verify the data in the file
        with open(txt_file, "r") as f:
            b = f.read()
            print(b)

错误是:

Traceback (most recent call last):
  File "C:/Users/xxxxxx/Downloads/TEST2/Searchcombine.py", line 15, in <module>
    a = f.read()
  File "C:\Python\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 1060662: character maps to <undefined>

2 个答案:

答案 0 :(得分:0)

您可以在调用open()时尝试设置编码参数:

with open(txt_file, "r", encoding="utf-8") as f:

答案 1 :(得分:0)

尽管大多数文件不是最安全,但我通过在行ignore error中添加(txt_file, "r") as f:使其成为(txt_file, errors='ignore') as f:来解决它。