Python Forum

Full Version: The difference between os.path.join( and os.sep.join(
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
What is the difference between these 2?

1. with os.sep.join([dirpath, filename])

for (dirpath, dirnames, filenames) in os.walk(path):
    for filename in filenames:
        if filename.endswith('.jpg'): 
            list_of_files[filename] = os.sep.join([dirpath, filename])
2. os.path.join(dirpath, filename)

for (dirpath, dirnames, filenames) in os.walk(path):
    for filename in filenames:
        if filename.endswith('.jpg'): 
            list_of_files[filename] = os.path.join(dirpath, filename)
Both seem to produce the same result. Is either preferable??
os.path.join is preferable.

os.sep is simply a character. So os.sep.join is just the normal string join.

>>> type(os.sep)
<class 'str'>
>>> os.sep.join(["foobar", "/foo/baz/", "whatever"])
'foobar//foo/baz//whatever'
os.path.join joins them with some more intelligence. If you have multiple separators, it will take it down to one. If you have a component that is an absolute path (starts with a separator), it will ignore the paths before it, etc.

>>> os.path.join("foobar", "/foo/baz/", "whatever")
'/foo/baz/whatever'
Thanks!!