How to create utf-8 files in python?
三叔
三叔 2017-06-14 10:53:28
0
2
1080
# 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?

三叔
三叔

reply all(2)
迷茫

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)

小葫芦

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编码储存中文字符
>>> 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template