Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.path.join not properly formatting path

Tags:

python

windows

I'm writing a command-line directory navigator for Windows in Python and struggling a bit with 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. 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.

like image 983
bkaiser Avatar asked Nov 19 '12 19:11

bkaiser


People also ask

What is os path join?

os. path. join combines path names into one complete path. This means that you can merge multiple parts of a path into one, instead of hard-coding every path name manually.

What is os path Abspath?

Given an empty string, os. path. abspath returns the current directory, which is what you want, since the script was run from the current directory. Like the other functions in the os and os.

What is os path Normpath?

os.path. normpath (path) Normalize a pathname by collapsing redundant separators and up-level references so that A//B , A/B/ , A/./B and A/foo/../B all become A/B . This string manipulation may change the meaning of a path that contains symbolic links. On Windows, it converts forward slashes to backward slashes.

Why do we need os path join?

Using os. path. join makes it obvious to other people reading your code that you are working with filepaths. People can quickly scan through the code and discover it's a filepath intrinsically.


1 Answers

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.

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? It splits the drive letter from the path.

like image 124
BrenBarn Avatar answered Sep 21 '22 10:09

BrenBarn