python - 文件以错误的编码加载utf-8

时间:2017-06-21 05:46:43

标签: python encoding utf-8 pycharm

我是一个很新的编程,我不明白我得到的这个错误信息,file was loaded in the wrong encoding utf-8或它不是代码中的错误信息,但我在我写的新的.txt文件中得到它找到的所有关键词。 .txt文件获取超过4000行的信息,我在另一个程序中将Excel排序,然后将其发送到Access。消息意味着什么剂量,是否有办法解决它?感谢

我正在使用pycharm和anaconda36

enter image description here

import glob


def LogFile(filename, tester):

    data = []
    with open(filename) as filesearch:   # open search file
        filesearch = filesearch.readlines()   # read file
    file = filename[37:]
    for line in filesearch:
        if tester in line:   # extract "Create Time"
            short = line[30:]
            data.append(short)   # store all found wors in array

    print (file)

    with open('Msg.txt', 'a') as handler:  # create .txt file

        for i in range(len(data)):
            handler.write(f"{file}|{data[i]}")


# open with 'w' to "reset" the file.
with open('LogFile.txt', 'w') as file_handler:
    pass
# ---------------------------------------------------------------------------------

for filename in glob.glob(r'C:\Users\Documents\Access\\GTX797\*.log'):
    LogFile(filename, 'Sending Request: Tester')

1 个答案:

答案 0 :(得分:0)

我在pyCharm中遇到了同样的错误,并在创建文件时通过指定UTF-8来修复它。您需要导入编解码器才能执行此操作。

import codecs

with codecs.open(‘name.txt', 'a', 'utf-8-sig') as f: