开发者

How to check wether a path represented by a QString with german umlauts exists?

i get a QString which represents a directory from a QLineEdit. Now i want to check wether a certain file exists开发者_JAVA百科 in this directory. But if i try this with os.path.exists and os.path.join and get in trouble when german umlauts occur in the directory path:

#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))

How would you check if the file exists, when you might encounter german umlauts?


I was getting no where with this on my Ubuntu box with an ext3 filesystem. So, I guess make sure the filesystem supports unicode filenames first, or else I believe the behavior is undefined?

>>> os.path.supports_unicode_filenames
True

If that's True, you should be able to pass unicode strings to the os.path calls directly:

>>> 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

You should look at QString.toUtf8 and maybe pass the returned value through os.path.normpath before handing it over to os.path.join

Good Luck!

nm, it works fine on my ubuntu box as well...

>>> 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜