csv.writer编码为'utf-8',但读取编码为'cp1252' [英] csv.writer encoding 'utf-8', but reading encoding 'cp1252'
问题描述
当写入文件时,我使用以下代码.这是大写字母,但我也看到了小写的 utf-8
编码.
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
.
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'])
并检查* .csv是否实际上是 utf-8
,我将其打开并阅读:
And to check if the *.csv is in fact utf-8
I open it and read it:
with open(path_to_file, 'r') as r:
print(r)
我期望编码为 utf-8
,但我得到:
I'm expecting the encoding to be utf-8
, but I get:
<_io.TextIOWrapper name='C:\\Users\\jpm\\Downloads\\c19_Vaccine_Current.csv' mode='r' encoding='cp1252'>
我几乎从文档.拥有* .csv文件作为 utf-8
至关重要,但是事实并非如此.
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.
推荐答案
还必须在开放位置上指定编码.打开文件的编码取决于平台,在Windows上似乎是cp1252.
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.
您可以使用以下命令检查默认平台编码:(在Mac上为utf-8)
You can check the default platform encoding with this: (on Mac it gives utf-8)
>>>import locale
>>>locale.getpreferredencoding(False)
'UTF-8'
with open('file', 'r', encoding='utf-8'):
...
with open('file', 'w', encoding='utf-8'):
...
这篇关于csv.writer编码为'utf-8',但读取编码为'cp1252'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!