Python Forum
The difference between os.path.join( and os.sep.join(
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The difference between os.path.join( and os.sep.join(
#1
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??
Reply
#2
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'
Pedroski55 and buran like this post
Reply
#3
Thanks!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  os.path.join() 'NoneType' confusion gowb0w 11 1,530 Sep-22-2023, 11:13 PM
Last Post: deanhystad
  Formatting outputs created with .join command klairel 2 614 Aug-23-2023, 08:52 AM
Last Post: perfringo
  ''.join and start:stop:step notation for lists ringgeest11 2 2,414 Jun-24-2023, 06:09 AM
Last Post: ferdnyc
  Will JoinableQueue.join() always notice the counter reaching 0? RobinVeer 1 755 Oct-07-2022, 09:28 AM
Last Post: Larz60+
  how to join by stack multiple types in numpy arrays caro 1 1,138 Jun-20-2022, 05:02 PM
Last Post: deanhystad
  Join dataframes... So simple but I can't work it out! snakes 1 1,359 Oct-27-2021, 09:15 AM
Last Post: snakes
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,191 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  os.path.join - errors out tester_V 4 2,684 Nov-29-2020, 08:57 AM
Last Post: DeaD_EyE
  os.path.join qmfoam 2 2,345 Nov-08-2020, 04:03 PM
Last Post: qmfoam
  how does .join work with list and dictionaries gr3yali3n 7 3,278 Jul-07-2020, 09:36 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020