Python Forum

Full Version: os.path.join
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This has me confused as to why it does not work:
import os

PARENT_DIR = '/Volumes/Sidekick/SEER/Trip'
SOURCE_DIR = '/data/source'

# first do as concatenation and show result

OUT_DIR = PARENT_DIR + SOURCE_DIR
Print(OUT_DIR) 
Output:
>> /Volumes/Sidekick/SEER/Trip/data/source <<
# Now, do using os.path.join and show result
OUT1_DIR = os.path.join(PARENT_DIR, SOURCE_DIR)
Print(OUT1_DIR)
Output:
>> /data/source <<
Anyone have any ideas on what is happening?

TNX
Quote:Help on function join in module posixpath:

join(a, *p)
Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded.
An empty last part will result in a path that
ends with a separator.

Your second path starts with a separator, so it is considered an absolute path. Therefore the first path is discarded.

>>> os.path.join('/Volumes/Sidekick/SEER/Trip', '/data/source')
'/data/source'
>>> os.path.join('/Volumes/Sidekick/SEER/Trip', 'data/source')
'/Volumes/Sidekick/SEER/Trip/data/source'
(Nov-07-2020, 06:14 PM)bowlofred Wrote: [ -> ]
Quote:Help on function join in module posixpath:

join(a, *p)
Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded.
An empty last part will result in a path that
ends with a separator.

Your second path starts with a separator, so it is considered an absolute path. Therefore the first path is discarded.

>>> os.path.join('/Volumes/Sidekick/SEER/Trip', '/data/source')
'/data/source'
>>> os.path.join('/Volumes/Sidekick/SEER/Trip', 'data/source')
'/Volumes/Sidekick/SEER/Trip/data/source'

Thank you