Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't os.path.join() work in this case?

Tags:

python

path

The below code will not join, when debugged the command does not store the whole path but just the last entry.

os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/') 

When I test this it only stores the /new_sandbox/ part of the code.

like image 528
chrisg Avatar asked Dec 22 '09 11:12

chrisg


People also ask

Why does os path join not work?

join function won't work if a component is an absolute path because all previous components are thrown away and joining continues from the absolute path component. The path strings shouldn't start with a slash. If they start with a slash, then they are believed an “absolute path” and everything before them is dumped.

How does os path join work?

path. join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator ('/') following each non-empty part except the last path component.

Does os path join return a string?

os. path. join returns a string; calling the join method of that calls the regular string join method, which is entirely unrelated.

Why do we use 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

The latter strings shouldn't start with a slash. If they start with a slash, then they're considered an "absolute path" and everything before them is discarded.

Quoting the Python docs for os.path.join:

If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

Note on Windows, the behaviour in relation to drive letters, which seems to have changed compared to earlier Python versions:

On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that 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.

like image 141
Craig McQueen Avatar answered Sep 20 '22 04:09

Craig McQueen