# coding=utf-8 ##以utf-8编码储存中文字符
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
The above code can only create text files in ANSI format. How to create UTF-8 files?
迷茫2017-06-14 10:55:28
In fact, the code of the subject can create UTF-8 files, but because there is no content written in the file, the empty txt file does not have encoding. Write some UTF characters and try again and it will be OK
f=codecs.open(path,'w', 'UTF-8')
f.write("中文")
f.close()
Open the c.txt file again and it will be UTF-8.
(Python3.4)
高洛峰2017-06-14 10:55:28
encoding='utf8'
>>> with open('utf8.txt','w', encoding='utf8') as w:
w.write('以utf-8编码储存中文字符')
14
>>> with open('utf8.txt','r', encoding='utf8') as r:
print(r.encoding)
print(r.read())
utf8
以utf-8编码储存中文字符
>>>