2010-04-13 64 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