简体   繁体   English

UnicodeDecodeError:保存到python文件中

[英]UnicodeDecodeError: save to file in python

i want to read file, find something in it and save the result, but when I want to save it it give me a error 我想读取文件,在其中找到某些内容并保存结果,但是当我要保存文件时,它给我一个错误
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 19: ordinal not in range(128)

Code to save to file: 保存到文件的代码:
fileout.write((key + ';' + nameDict[key]+ ';'+src + alt +'\\n').decode('utf-8'))

What can I do to fix it? 我该如何解决?
Thank you 谢谢

You are trying to concatenate unicode values with byte strings, then turn the result to unicode, to write it to a file object that most likely only takes byte strings. 您试图将unicode值与字节字符串连接起来,然后将结果转换为unicode,以将其写入最有可能仅使用字节字符串的文件对象中。

Don't mix unicode and byte strings like that . 不要像这样混合unicode和字节字符串

Open the file to write to with io.open() to automate encoding Unicode values, then handle only unicode in your code: 使用io.open()打开要写入的文件以自动编码Unicode值,然后处理代码中的unicode:

import io

with io.open(filename, 'w', encoding='utf8') as fileout:
    # code gathering stuff from BeautifulSoup

    fileout.write(u'{};{};{}{}\n'.format(key, nameDict[key], src, alt)

You may want to check out the csv module to handle writing out delimiter-separated values. 您可能需要检出csv模块以处理写出以定界符分隔的值。 If you do go that route, you'll have to explicitly encode your columns: 如果您遵循这种方法,则必须对列进行显式编码:

import csv

with open(filename, 'wb') as fileout:
    writer = csv.writer(fileout, delimiter=';')
    # code gathering stuff from BeautifulSoup

    row = [key, nameDict[key], src + alt]
    writer.writerow([c.encode('utf8') for c in row])

If some of this data comes from other files, make sure you also decode to Unicode first; 如果其中一些数据来自其他文件,请确保还先解码为Unicode。 again, io.open() to read these files is probably the best option, to have the data decoded to Unicode values for you as you read. 同样, io.open()读取这些文件可能是最好的选择,以便在读取时将数据解码为Unicode值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM