python 怎樣創建utf-8的文件?
問題描述
# coding=utf-8 ##以utf-8編碼儲存中文字符import osimport codecspath = '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
以上代碼只能創建ANSI格式的文本文件,怎樣長創建UTF-8的文件?
問題解答
回答1:其實題主的代碼可以創建UTF-8的文件,只是由于沒有往文件里寫內容,空的txt文件不存在編碼,寫一些UTF字符再試試就OK了
f=codecs.open(path,’w’, ’UTF-8’) f.write('中文') f.close()
再打開c.txt文件就是UTF-8了。(Python3.4)
回答2: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編碼儲存中文字符>>>
相關文章:
1. css3 - [CSS] 動畫效果 3D翻轉bug2. python - Django分頁和查詢參數的問題3. javascript - 百度echarts series數據更新問題4. MySQL客戶端吃掉了SQL注解?5. javascript - JS設置Video視頻對象的currentTime時出現了問題,IE,Edge,火狐,都可以設置,反而chrom卻...6. php自學從哪里開始?7. python小白的基礎問題 關于while循環的嵌套8. 求大神幫我看看是哪里寫錯了 感謝細心解答9. phpstady在win10上運行10. javascript - 圖片能在網站顯示,但控制臺仍舊報錯403 (Forbidden)
