Wie erstelle ich UTF-8-Dateien in Python?
三叔
三叔 2017-06-14 10:53:28
0
2
1120
# 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

Der obige Code kann nur Textdateien im ANSI-Format erstellen.

三叔
三叔

Antworte allen(2)
迷茫

其实题主的代码可以创建UTF-8的文件,只是由于没有往文件里写内容,空的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('以utf-8编码储存中文字符')

    
14

>>> with open('utf8.txt','r', encoding='utf8') as r:
    print(r.encoding)
    print(r.read())

    
utf8
以utf-8编码储存中文字符
>>> 
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage