# coding=utf-8 ##以u(píng)tf-8編碼儲(chǔ)存中文字符
import os
import codecs
path = "d:/Python/c.txt"
try:
f=codecs.open(path,'w', 'UTF-8')
f.close()
except Exception as e:
print(e)
os.system('pause')
Python 3.6.1
Der obige Code kann nur Textdateien im ANSI-Format erstellen.
其實(shí)題主的代碼可以創(chuàng)建UTF-8的文件,只是由于沒有往文件里寫內(nèi)容,空的txt文件不存在編碼,寫一些UTF字符再試試就OK了
f=codecs.open(path,'w', 'UTF-8')
f.write("中文")
f.close()
再打開c.txt文件就是UTF-8了。
(Python3.4)
encoding='utf8'
>>> with open('utf8.txt','w', encoding='utf8') as w:
w.write('以u(píng)tf-8編碼儲(chǔ)存中文字符')
14
>>> with open('utf8.txt','r', encoding='utf8') as r:
print(r.encoding)
print(r.read())
utf8
以u(píng)tf-8編碼儲(chǔ)存中文字符
>>>