[英]csv.writer encoding 'utf-8', but reading encoding 'cp1252'
When writing to a file I use the following code.写入文件时,我使用以下代码。 Here it's upper case, but I've also seen the encoding in lower case
utf-8
.这里是大写,但我也看到了小写
utf-8
的编码。
path_to_file = os.path.join(r'C:\Users\jpm\Downloads', 'c19_Vaccine_Current.csv')
#write to file
with open(path_to_file, 'w', newline='', encoding='UTF-8') as csvfile:
f = csv.writer(csvfile)
#write the headers of the csv file
f.writerow(['County','AdminCount','AdminCountChange', 'RollAvg', 'AllocDoses', 'FullyVaccinated', 'FullyVaccinatedChange', 'ReportDate', 'Pop', 'PctVaccinated', 'LHDInventory', 'CommInventory',
'TotalInventory', 'InventoryDate'])
And to check if the *.csv is in fact utf-8
I open it and read it:为了检查 *.csv 实际上是
utf-8
我打开它并阅读它:
with open(path_to_file, 'r') as r:
print(r)
I'm expecting the encoding to be utf-8
, but I get:我期望编码为
utf-8
,但我得到:
<_io.TextIOWrapper name='C:\\Users\\jpm\\Downloads\\c19_Vaccine_Current.csv' mode='r' encoding='cp1252'>
I pretty much borrowed the code from this answer .我几乎从这个答案中借用了代码。 And I've also read the doc .
而且我还阅读了文档。 It's crucial that I have the *.csv file as
utf-8
, but that doesn't appear to be the case.至关重要的是,我将 *.csv 文件作为
utf-8
,但情况似乎并非如此。
The encoding has to be specified on an open as well.编码也必须在打开时指定。 The encoding in which a file is opened is platform dependant, it would seem to be cp1252 on windows.
打开文件的编码取决于平台,它似乎是 windows 上的 cp1252。
You can check the default platform encoding with this: (on Mac it gives utf-8)您可以使用以下命令检查默认平台编码:(在 Mac 上,它提供 utf-8)
>>>import locale
>>>locale.getpreferredencoding(False)
'UTF-8'
with open('file', 'r', encoding='utf-8'):
...
with open('file', 'w', encoding='utf-8'):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.