1

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

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235

1 Answers1

1

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.

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
  • 1
    Thanks, the light dawns. I had read the doc before I posted, and still didn't get it. After reading your answer I used isabs('path') to play around and think I understand now. Starting with the path separator, in my case '/', refers to the root, which contains on Ubunto folders bin and home, among others. Starting without it refers to the current working directory. Many thanks. – Persistent at Python Apr 16 '19 at 19:49