python将文本数据写入文本文件

时间:2017-08-24 14:15:08

标签: python file

我在python中有这段代码:

def write_to_log_file(text):
    with open ("C:\Users\Administrator\Desktop\log.txt",mode='w') as file:
        file.write(text)

然而,当我运行此代码时,我收到以下错误:

line 13, in write_to_log_file
    file.write(text)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 126: ordinal not in range(128)

1 个答案:

答案 0 :(得分:2)

Reference

def write_to_log_file(text):
    with open ("C:\Users\Administrator\Desktop\log.txt",mode='w') as file:
        file.write(text.encode('utf8'))