Python Forum
os.path.join - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: os.path.join (/thread-30815.html)



os.path.join - qmfoam - Nov-07-2020

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


RE: os.path.join - bowlofred - Nov-07-2020

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'



RE: os.path.join - qmfoam - Nov-08-2020

(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