gpt4 book ai didi

python - Unicode编码错误: 'charmap' codec can't encode character '\u5347' in position 68: character maps to

转载 作者:行者123 更新时间:2023-12-01 03:14:53 25 4
gpt4 key购买 nike

我是Python新手。我从 SQL Server 读取数据,然后将数据写入 csv 文件。表行同时包含数字、字符串和日期时间值。我尝试了不同的方法来写入数据。例如,

#method 1
import pandas as pd

df = pd.DataFrame(table, columns=["colummn"])

df.to_csv('list.csv', index=False)*

#method 2
import csv

fl = open('OnlineplayDatabase.csv', 'w')

writer = csv.writer(fl)

for row in table:

writer.writerow(row)

fl.close()

两种方法都可以正常工作。但是,当某些行包含中文字符时(请参见下面的示例),我收到编码错误。错误消息显示:

codecs.charmap_encode(input,self.errors,encoding_table)[0]

#Error Code
UnicodeEncodeError: 'charmap' codec can't encode character '\u5347' in position 68: character maps to <undefined>

我尝试使用 utf-8 对行中的字段进行编码。但有些字段是数字。

非常感谢您的帮助!

('120.239.9.116  ',
'gyandroid ',
4,
9,
'Dalvik/1.6.0(Linux;U;Android4.4.2;升级版Build/KVT49L) datetime.datetime(2016, 6, 11, 20, 54, 19),
datetime.datetime(2016, 6, 11, 20, 56, 53),
11521.0)

最佳答案

尝试方法#2:

#method 2
import csv

fl = open('OnlineplayDatabase.csv', 'w', encoding='utf8') #set the encoding to utf8
writer = csv.writer(fl)

for row in table:
writer.writerow(row)

fl.close()

另外看看这个 - http://www.pgbovine.net/unicode-python-errors.htm

关于python - Unicode编码错误: 'charmap' codec can't encode character '\u5347' in position 68: character maps to <undefined>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42546798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com