Python 在Windows上运行时,如何强制熊猫1.0.3写入编码为UTF-8的csv?

Python 在Windows上运行时,如何强制熊猫1.0.3写入编码为UTF-8的csv?,python,pandas,encoding,utf-8,Python,Pandas,Encoding,Utf 8,熊猫1.0.3 Python 3.7.6 代码: 当我在mac上运行时,它工作正常,以立方米为计量单位显示csv: uom M³ 但在windows上运行时,尝试读取写入的文件失败: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 7: invalid start byte 相反,df.to_csv似乎忽略了我将其编码为utf-8的请求,而是将其编写为iso-8859-1。这在windows中用于读取文

熊猫1.0.3

Python 3.7.6

代码:

当我在mac上运行时,它工作正常,以立方米为计量单位显示csv:

uom
M³
但在windows上运行时,尝试读取写入的文件失败:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 7: invalid start byte
相反,df.to_csv似乎忽略了我将其编码为utf-8的请求,而是将其编写为iso-8859-1。这在windows中用于读取文件:

>>> csv_file = open('encoded.csv', 'r', encoding='iso-8859-1')
>>> print(csv_file.read())
uom
M³

在Windows上运行时,如何强制熊猫1.0.3编写编码为UTF-8的csv?

谢谢@Quang Hoang,你是对的。首先打开编码为utf-8的文件可以:

import pandas as pd

df = pd.DataFrame(data={'uom': ['M³']})
with open('encoded.csv', 'w', encoding='utf-8') as csv_file:
    df.to_csv(csv_file, index=False, line_terminator='\n')

with open('encoded.csv', 'r', encoding='utf-8') as csv_file:
    print(csv_file.read())
如果让pandas为您创建文件,它看起来只关注
编码
参数,但在我的例子中,我是先创建文件的


有道理。

您打开文件写入时没有
编码
?另外,
df.to_csv('path_to_file.csv',encoding='utf-8'
)有什么问题吗?注意:您不需要在打开时使用
(…
上下文管理器,用于
到_csv
,除非您也在对文件执行其他操作,否则熊猫会在其上处理上下文own@G.Anderson是的,我对这个文件做了一些其他的事情,但是我把它归结为这个更简单的版本发布在这里。谢谢你的反馈!
import pandas as pd

df = pd.DataFrame(data={'uom': ['M³']})
with open('encoded.csv', 'w', encoding='utf-8') as csv_file:
    df.to_csv(csv_file, index=False, line_terminator='\n')

with open('encoded.csv', 'r', encoding='utf-8') as csv_file:
    print(csv_file.read())