简体   繁体   English

os.path.join没有正确格式化路径

[英]os.path.join not properly formatting path

I'm writing a command-line directory navigator for Windows in Python and struggling a bit with os.path.join. 我正在用Python编写一个Windows命令行目录导航器,并在os.path.join中苦苦挣扎。 Here's, in essence, what I'm trying to do: 从本质上讲,这就是我要做的事情:

abspath = "C:\Python32\Projects\ls.py"
abspath = abspath.split('\\')
print(abspath) #this prints ['C:', 'Python32', 'Projects', 'ls.py']

if(options.mFlag):  
        print(os.path.join(*abspath)) #this prints C:Python32\Projects\ls.py
        m = time.ctime(os.path.getmtime(os.path.join(*abspath))) #this throws an exception

The problem is that os.path.join is not inserting a '/' after 'C:' and I can't figure out why. 问题是os.path.join没有在'C:'之后插入'/',我无法弄清楚原因。 Any help? 有帮助吗?

Edit: In case anyone in the future comes here looking for a solution, I just added os.sep after "C:" instead of hardcoding a backslash and that worked. 编辑:如果将来有人在这里寻找解决方案,我只是在“C:”之后添加了os.sep,而不是硬编码反斜杠而且有效。

From the documentation : 文档

Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\\foo. 请注意,在Windows上,由于每个驱动器都有一个当前目录, os.path.join("c:", "foo")表示相对于驱动器C上当前目录的路径:(c:foo),而不是c :\\ FOO。

It's a little hard to tell what you're trying to accomplish, since all your code seems to be aiming at is to split the path and then put it back together exactly the way it was, in which case why split it in the first place? 有点难以分辨你要完成什么,因为你的所有代码似乎都是为了分割路径,然后将其完全按照原来的方式重新组合在一起,在这种情况下为什么要将它分开放在第一位? But maybe os.path.splitdrive will help you? 但也许os.path.splitdrive可以帮到你吗? It splits the drive letter from the path. 它会从路径中分割驱动器号。

The docs ( http://docs.python.org/2/library/os.path.html ) specify this behaviour: 文档( http://docs.python.org/2/library/os.path.html )指定了此行为:

Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\\foo. 请注意,在Windows上,由于每个驱动器都有一个当前目录,os.path.join(“c:”,“foo”)表示相对于驱动器C上当前目录的路径:(c:foo),而不是c :\\ FOO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM