2010-04-13 47 views
1

我得到一個QString代表QLineEdit中的一個目錄。現在我想檢查這個目錄中是否存在某個文件。但如果我嘗試這與os.path.exists和os.path.join和惹上麻煩時,德國的變音符號出現在目錄路徑:如何檢查使用德語變音符號的QString代表的路徑?

#the direcory coming from the user input in the QLineEdit 
#i take this QString to the local 8-Bit encoding and then make 
#a string from it 
target_dir = str(lineEdit.text().toLocal8Bit()) 
#the file name that should be checked for 
file_name = 'some-name.txt' 
#this fails with a UnicodeDecodeError when a umlaut occurs in target_dir 
os.path.exists(os.path.join(target_dir, file_name)) 

你將如何檢查文件是否存在,時可能會遇到德語變音器?

回答

1

我沒有在帶有ext3文件系統的Ubuntu盒子上找到這個地方。所以,我想確保文件系統首先支持unicode文件名,否則我相信這種行爲是不確定的?

>>> os.path.supports_unicode_filenames 
True 

如果這是真的,你應該能夠通過unicode字符串到os.path中直接調用:

>>> print u'\xf6' 
ö 
>>> target_dir = os.path.join(os.getcwd(), u'\xf6') 
>>> print target_dir 
C:\Python26\ö 
>>> os.path.exists(os.path.join(target_dir, 'test.txt')) 
True 

你應該看看QString.toUtf8,也許通過os.path中傳遞返回值。 normpath將它交給os.path.join之前

祝你好運!

納米,它在我的Ubuntu箱正常工作,以及...

>>> os.path.supports_unicode_filenames 
False 
>>> target_dir = os.path.join(os.getcwd(), u'\xf6') 
>>> print target_dir 
/home/clayg/ö 
>>> os.path.exists(os.path.join(target_dir, 'test')) 
True 
+0

我現在還沒有在我的工作,嘗試的事情了,但我肯定會給你的方法一試。此外,我發現這一點,它提供完全讓PyQt檢查文件和處理變音符號。 http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qfileinfo.html#exists – mamachanko 2010-04-14 14:55:17

相關問題