在写文件时更改编码
我正在写一个文件:
with open("test_%s.tem" %i, "w") as f1:
....
f1.close()
我想把文件的编码转换成UCS-2小端格式。请问在open()或close()函数里可以做到吗?有什么建议吗?
2 个回答
1
在Python 2中,你可以使用codecs.open这个方法,并且需要设置一个叫encoding的参数。
如果你在用Python 3,只需要在open这个方法里设置encoding参数就可以了。
UCS-2是UTF-16的一部分,所以你可以试着把参数值设置为'UTF-16'
。
2
在Python 3
中,根据文档说明:https://docs.python.org/3/library/functions.html#open
你可以通过编码参数来指定文件的编码方式。
with open("test_%s.tem" %i, "w", encoding="utf16") as f1: