1

我得到一个 QString,它代表来自 QLineEdit 的目录。现在我想检查这个目录中是否存在某个文件。但是,如果我尝试使用 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 机器上,我对此一无所知。所以,我想确保文件系统首先支持 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

祝你好运!

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