2011-04-02 97 views
3

如何打開一個的unicode命名的文件(空間)從的Python腳本下內的Windows 打開一個unicode名爲xls文件?
文件名,例如:Hello עולם.xls的Python:從腳本

對於非Unicode非間隔xls文件,os.system(filename)效果很好。
對於非Unicode空間xls文件,os.system('"'+filename+'"')效果很好。

但對於Unicode空間xls文件...

兩個os.system(filename)subprocess.call(new_filename)給予:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 12-13: ordinal not in range(128)

os.system(new_filename.encode('UTF-8'))給出:

'Hello' is not recognized as an internal or external command, operable program or batch file.

subprocess.call(new_filename.encode('UTF-8'))給出:

WindowsError: [Error 2] The system cannot find the file specified

回答

6

os.startfile()由布拉德利(+1)提到,但一定要傳遞一個Unicode字符串,而不是一個字節的字符串。

Windows NT的文件名是本身使用Unicode,和Windows上的Python已經(與大多數其他腳本語言)具體支持內置傳遞Unicode的字符串放到期待文件名的API:

os.startfile(u'Hello \u05e2\u05d5\u05dc\u05dd.xls') # u'Hello עולם.xls' 

如果在傳遞它將轉到標準C stdio庫,該庫在Microsoft C運行時將使用機器的缺省字符集(又稱ANSI代碼頁)將字節字符串映射到Unicode文件名,這是getfilesystemencoding()正在返回的內容。如果文件名中的每個字符都可以在ANSI代碼頁中表示,但這種情況仍然有效,但示例文件名對於除希伯來語安裝的Windows以外的任何內容都將失敗。

不幸的是,相同的Unicode支持不適用於system()subprocess。但在這種情況下,您可能不需要使用命令行。

+2

你對這個主題的知識令人印象深刻。 – 2011-04-02 11:56:16