views:

104

answers:

1

Hey,

i get a QString which represents a directory from a QLineEdit. Now i want to check wether a certain file exists 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?

A: 

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
clayg
I haven't yet been at my job to try things out but i'll definitely give your approach a try. Furthermore i have found this, which offers to leave it completely to PyQt to check for the file and deal with umlauts. http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qfileinfo.html#exists
MB_