2016-01-07 56 views
3

我通過文件夾遞歸併收集文檔名稱和一些其他要加載到數據庫中的數據。如何將外部編碼字符寫入文本文件

import os 
text_file = open("Output.txt", "w") 

dirName = 'D:\\' 
for nextDir, subDir, fileList in os.walk(dirName): 
    for fname in fileList: 
     text_file.write(fname + '\n') 

的問題是,一些文件名稱有外文字符,如:

RC-0964_1000 Tưởng thưởng Diamond trẻ nhất Việt Nam - Đặng Việt Thắng và Trần Thu Phương 

而且

RC-1046 安麗2013ARTISTRY冰上雅姿盛典-愛裏歐娜.薩維琴科_羅賓.索爾科維【Suit & Tie】.mp4 

而且上面的代碼讓我在最後一行此錯誤:

UnicodeEncodeError: 'charmap' codec can't encode characters at positions ##-##:character maps to (undefined) 

我試過了到

  • temp = fname.endcode(utf-8)
  • temp = fname.decode(utf-8)
  • temp = fname.encode('ascii','ignore') temp2 = temp.decode('ascii')
  • temp =unicode(fname).encode('utf8')

我怎麼能寫這個劇本寫的所有字符的文件?我是否需要更改正在寫入的文件或我正在寫入的字符串,以及如何操作?

這些名字可以成功地粘貼到文件中,爲什麼Python不會將它們寫入?

+2

您使用的是哪個版本的Python? – Rockybilly

+0

我使用的是版本3.4 –

+0

[Python:將Unicode文本寫入文本文件?]的可能重複(http://stackoverflow.com/questions/6048085/python-write-unicode-text-to-a-text-文件) – roeland

回答

4

由於是Python 3,請選擇支持所有Unicode的編碼。在Windows上,至少缺省值是依賴於語言環境的,例如cp1252,並且對於像中文這樣的字符將失敗。

text_file = open("Output.txt", "w", encoding='utf8') 
+0

我不敢相信它是如此簡單。謝謝! –

1

默認情況下,text_file使用locale.getpreferredencoding(False)(的Windows ANSI代碼頁,你的情況)。

os.walk()如果在Windows上輸入路徑是Unicode,則使用Unicode API,因此它可能會生成無法使用Windows代碼頁(例如導致UnicodeEncodeError: 'charmap' codec can't encode錯誤的cp1252)表示的名稱。 8位編碼(如cp1252)只能表示256個字符,但有超過一百萬個Unicode字符。

要修復它,請使用可以表示給定名稱的字符編碼。 utf-8,utf-16字符編碼可以表示所有的Unicode字符。您可能更喜歡Windows上的utf-16,例如,以便notepad.exe能夠正確顯示文件:

with open('output.txt', 'w', encoding='utf-16') as text_file: 
    print('\N{VICTORY HAND}', file=text_file) 
相關問題