Dogcam
Dogcam

Reputation: 13

Why are os.path.join() on a list and os.path.sep.join() on a list not functionally identical?

I'm working on a program that needs to split and rejoin some file paths, and I'm not sure why os.path.join(*list) and os.path.sep.join(list) produce different results when there is a drive letter present in the separated path.

import os

path = 'C:\\Users\\choglan\\Desktop'

separatedPath = path.split(os.path.sep)
# ['C:', 'Users', 'choglan', 'Desktop']

path = os.path.sep.join(separatedPath)
# C:\\Users\\choglan\\Desktop
print(path)

path = os.path.join(*separatedPath)
# C:Users\\choglan\\Desktop
print(path)

Why does this happen? And should I just use os.path.sep.join(list) for my program even though os.path.join(*list) seems to be more commonly used?

Upvotes: 1

Views: 1444

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308432

os.path.sep isn't an independent object with its own methods, it's a string. So the join method on it just pastes together the strings with that character between them.

>>> type(os.path.sep)
<class 'str'>

You can use join from any string.

>>> '|'.join(separatedPath)
'C:|Users|choglan|Desktop'

Upvotes: 0

user2357112
user2357112

Reputation: 281586

os.path.join is not intended to be the inverse of path.split(os.path.sep). If you read the docs, you'll find a description of a much more complicated process than just sticking os.path.sep between the arguments. The most relevant part is the following:

On Windows... 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.

You should probably be using pathlib.PurePath(path).parts rather than path.split(os.path.sep).

Upvotes: 1

Related Questions