gpt4 book ai didi

python - CSV 阅读器在前几个字符中捡垃圾

转载 作者:行者123 更新时间:2023-12-04 13:18:28 24 4
gpt4 key购买 nike

我正在尝试读取 CSV 文件的第一行并将其分配给 header . CSV 文件如下所示:

TIME,DAY,MONTH,YEAR
"3:21","23","FEB","2018"
"3:23","23","FEB","2018"
...

这是代码:
import csv

with open("20180223.csv") as csvfile:
rdr = csv.reader(csvfile)
header = next(rdr)
print(header)

我希望输出看起来像:
['TIME', 'DAY', 'MONTH', 'YEAR']

但是输出如下所示:
['TIME', 'DAY', 'MONTH', 'YEAR']

我错过了什么?

最佳答案

第一个字符是 Byte order mark特点。

尝试这个:

with open("20180223.csv", encoding="utf-8-sig") as csvfile:

这个建议有点隐藏在 documentation 中。 ,但它在那里:

In some areas, it is also convention to use a “BOM” at the start of UTF-8 encoded files; the name is misleading since UTF-8 is not byte-order dependent. The mark simply announces that the file is encoded in UTF-8. Use the ‘utf-8-sig’ codec to automatically skip the mark if present for reading such files.

关于python - CSV 阅读器在前几个字符中捡垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49543139/

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