如何检查由带德语变音符号的 QString 表示的路径是否存在?
我得到一个 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))
当您可能遇到德语变音符号时,您将如何检查文件是否存在?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我的带有 ext3 文件系统的 Ubuntu 机器上,我没有得到任何结果。所以,我想首先确保文件系统支持 unicode 文件名,否则我认为该行为是未定义的?
如果这是真的,您应该能够直接将 unicode 字符串传递给 os.path 调用:
您应该查看 QString.toUtf8 并可能在将返回值传递给 os.path.join 之前将其传递给 os.path.normpath
祝你好运!
nm,它在我的 ubuntu 盒子上也运行得很好......
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?
If that's True, you should be able to pass unicode strings to the os.path calls directly:
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...