簡體   English   中英

csv.writer 編碼“utf-8”,但讀取編碼“cp1252”

[英]csv.writer encoding 'utf-8', but reading encoding 'cp1252'

寫入文件時,我使用以下代碼。 這里是大寫,但我也看到了小寫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我打開它並閱讀它:

with open(path_to_file, 'r') as r:
    print(r)

我期望編碼為utf-8 ,但我得到:

<_io.TextIOWrapper name='C:\\Users\\jpm\\Downloads\\c19_Vaccine_Current.csv' mode='r' encoding='cp1252'>

我幾乎從這個答案中借用了代碼。 而且我還閱讀了文檔 至關重要的是,我將 *.csv 文件作為utf-8 ,但情況似乎並非如此。

編碼也必須在打開時指定。 打開文件的編碼取決於平台,它似乎是 windows 上的 cp1252。

您可以使用以下命令檢查默認平台編碼:(在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM