Persistent at Python
Persistent at Python

Reputation: 15

os.path.join seems sensitive to opening slash, why?

Adding a slash to Documents in os.join produces different results when I think it should not. Why?

Just trying to write code that does reasonable things for multiple users.

import os
# Initialize output files and folders, following principle of separating code from data
homeDir = os.path.expanduser('~')
targetDir = os.path.join(homeDir, '/Documents/Jeopardy/output')
print(targetDir)
# produces /Documents/Jeopardy/output  which is not expected
targetDir = os.path.join(homeDir, 'Documents/Jeopardy/output')
print(targetDir)
# produces /home/max/Documents/Jeopardy/output  which is expected

I expected both joins to produce /home/max/Documents/Jeopardy/output But the first one didn't. I must not understand the join doc, but I can't see why I get different outputs. thanks in advance

Upvotes: 1

Views: 125

Answers (1)

Brad Solomon
Brad Solomon

Reputation: 40878

From the join() docstring:

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

'/Documents/Jeopardy/output' is an absolute path, so the first part is discarded.

Behaviorally, using the relative rather than absolute path arguably makes more sense; it doesn't make a ton of sense to prepend anything to an absolute path, since it already starts at the FS root.

Upvotes: 1

Related Questions