1

QLineEdit からディレクトリを表す QString を取得します。このディレクトリに特定のファイルが存在するかどうかを確認したいと思います。しかし、os.path.exists と os.path.join でこれを試してみると、ディレクトリ パスでドイツ語のウムラウトが発生したときに問題が発生します。

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

ドイツ語のウムラウトに遭遇する可能性がある場合、ファイルが存在するかどうかをどのように確認しますか?

4

1 に答える 1

1

ext3ファイルシステムを備えたUbuntuボックスでは、これでどこにも行きませんでした。したがって、ファイルシステムが最初にユニコードファイル名をサポートしていることを確認してください。そうしないと、動作が未定義であると思いますか?

>>> os.path.supports_unicode_filenames
True

それが 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.join に渡す前に os.path.normpath を介して渡す必要があります。

幸運を!

nm、私の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
于 2010-04-13T21:35:03.710 に答える