suchen

Heim  >  Fragen und Antworten  >  Hauptteil

Wie erstelle ich UTF-8-Dateien in Python?

# 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.

三叔三叔2800 Tage vor1117

Antworte allen(2)Ich werde antworten

  • 迷茫

    迷茫2017-06-14 10:55:28

    其实题主的代码可以创建UTF-8的文件,只是由于没有往文件里写内容,空的txt文件不存在编码,写一些UTF字符再试试就OK了

        f=codecs.open(path,'w', 'UTF-8')
        f.write("中文")
        f.close()

    再打开c.txt文件就是UTF-8了。
    (Python3.4)

    Antwort
    0
  • 高洛峰

    高洛峰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编码储存中文字符
    >>> 

    Antwort
    0
  • StornierenAntwort