簡體   English   中英

在Windows上的Python 3.4中處理Unicode文件名

[英]handling Unicode filenames in Python 3.4 on Windows

我試圖找到一種可靠的方法來在Windows中使用Python掃描文件,同時考慮到文件名中可能存在各種Unicode代碼點的可能性。 我已經看到了幾個針對此問題的建議解決方案,但是它們都無法解決我在掃描由實際軟件和用戶創建的文件名時遇到的所有實際問題。

下面的代碼示例是嘗試解脫並演示核心問題。 它在子文件夾中用我遇到的各種變化創建了三個文件,然后嘗試瀏覽該文件夾並顯示每個文件名以及文件內容。 嘗試讀取第三個測試文件時,它將崩潰,並帶有OSError [Errno 22] Invalid參數。

import os

# create files in .\temp that demonstrate various issues encountered in the wild
tempfolder = os.getcwd() + '\\temp'
if not os.path.exists(tempfolder):
    os.makedirs(tempfolder)
print('file contents', file=open('temp/simple.txt','w'))
print('file contents', file=open('temp/with a ® symbol.txt','w'))
print('file contents', file=open('temp/with these chars ΣΑΠΦΩ.txt','w'))

# goal is to scan the files in a manner that allows for printing
# the filename as well as opening/reading the file ...
for root,dirs,files in os.walk(tempfolder.encode('UTF-8')):
    for filename in files:
        fullname = os.path.join(tempfolder.encode('UTF-8'), filename)
        print(fullname)
        print(open(fullname,'r').read())

如代碼中所說,我只希望能夠顯示文件名並打開/讀取文件。 關於文件名的顯示,我不在乎特殊情況下Unicode字符是否正確呈現。 我只想以一種唯一標識正在處理的文件的方式打印文件名,並且不會因這些異常的文件名而引發錯誤。

如果注釋掉最后一行代碼,則此處顯示的方法將顯示所有三個文件名而不會出現錯誤。 但是,它不會以其他Unicode名稱打開文件。

有沒有一種方法可以在Python中可靠地顯示/打開所有這三種文件名變體? 我希望在那里,而我對Unicode微妙之處的有限了解使我無法看到它。

下面的工作正常, 如果你保存在聲明編碼的文件, 如果您使用支持正在顯示的字符的IDE或終端編碼。 請注意,這不必是UTF-8。 文件頂部的聲明僅是源文件的編碼。

#coding:utf8
import os

# create files in .\temp that demonstrate various issues encountered in the wild
tempfolder = os.path.join(os.getcwd(),'temp')
if not os.path.exists(tempfolder):
    os.makedirs(tempfolder)
print('file contents', file=open('temp/simple.txt','w'))
print('file contents', file=open('temp/with a ® symbol.txt','w'))
print('file contents', file=open('temp/with these chars ΣΑΠΦΩ.txt','w'))

# goal is to scan the files in a manner that allows for printing
# the filename as well as opening/reading the file ...
for root,dirs,files in os.walk(tempfolder):
    for filename in files:
        fullname = os.path.join(tempfolder, filename)
        print(fullname)
        print(open(fullname,'r').read())

輸出:

c:\\temp\simple.txt
file contents

c:\temp\with a ® symbol.txt
file contents

c:\temp\with these chars ΣΑΠΦΩ.txt
file contents

如果您使用的終端不支持對文件名中使用的字符進行編碼,則會得到UnicodeEncodeError 更改:

print(fullname)

至:

print(ascii(fullname))

並且您會看到文件名已正確讀取,但是無法在終端編碼中打印一個或多個符號:

'C:\\temp\\simple.txt'
file contents

'C:\\temp\\with a \xae symbol.txt'
file contents

'C:\\temp\\with these chars \u03a3\u0391\u03a0\u03a6\u03a9.txt'
file contents

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM