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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With