Os.path :你能解释一下这种行为吗? [英] Os.path : can you explain this behavior?
问题描述
我喜欢 Python,因为它包含电池,而且我经常使用内置函数来为我完成繁重的工作.
我一直很高兴使用 os.path 模块来处理文件路径,但最近我在 Ubuntu linux 下的 Python 2.5 上得到了意想不到的结果,同时处理表示 Windows 文件路径的字符串:
filepath = r"c:\ttemp\FILEPA~1.EXE"打印 os.path.basename(filepath)'c:\\ttemp\\FILEPA~1.EXE']打印 os.path.splitdrive(文件路径)('', 'c:\ttemp\\FILEPA~1.EXE')
WTF?
文件路径 = u"c:\ttemp\FILEPA~1.EXE" 和 filepath = "c:\ttemp\FILEPA~1.EXE" 的结果相同.
你有线索吗?Ubuntu 使用 UTF8,但我觉得它与它无关.也许我的 Python 安装搞砸了,但我没有对它进行任何我记得的特定调整.
如果你想在 linux 上操作 Windows 路径,你应该使用 ntpath 模块(这是在 windows 上作为 os.path 导入的模块 - posixpath 被导入作为 os.path 在 linux)
<预><代码>>>>导入路径>>>文件路径 = r"c:\ttemp\FILEPA~1.EXE">>>打印 ntpath.basename(文件路径)FILEPA~1.EXE>>>打印 ntpath.splitdrive(文件路径)('c:', '\\ttemp\\FILEPA~1.EXE')I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me.
I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths :
filepath = r"c:\ttemp\FILEPA~1.EXE"
print os.path.basename(filepath)
'c:\\ttemp\\FILEPA~1.EXE']
print os.path.splitdrive(filepath)
('', 'c:\ttemp\\FILEPA~1.EXE')
WTF ?
It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE".
Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.
If you want to manipulate Windows paths on linux you should use the ntpath module (this is the module that is imported as os.path on windows - posixpath is imported as os.path on linux)
>>> import ntpath
>>> filepath = r"c:\ttemp\FILEPA~1.EXE"
>>> print ntpath.basename(filepath)
FILEPA~1.EXE
>>> print ntpath.splitdrive(filepath)
('c:', '\\ttemp\\FILEPA~1.EXE')
这篇关于Os.path :你能解释一下这种行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!