8

I came across this python function os.path.join(). I wanted to know which was a preferred method of using it.

os.path.join(r'C:\\' , r'some_dir_in_C_folder') 

or

print os.path.join("C:\\" , "some_dir_in_C_folder\\")

TIA

3
  • 4
    There are multiple differences between the two code snippets, and it's not clear which difference is important to you. Is it the print? Or the raw strings? Or the backslash at the end of the path? Commented Jul 30, 2014 at 0:13
  • not print actually. i wanted to ultimately walk through this saved path when need arises. When i say saved, i mean i'd store it in a variable. Commented Jul 30, 2014 at 0:17
  • the top one is correct ... the point of os.path.join is that you dont need to worry about the separator ... as such using it largely defeats the purpose ... os.path.join is just a convenience wrapper around os.path.sep.join(["PATH","DIR1","DIR2",...]) Commented Jul 30, 2014 at 0:18

1 Answer 1

12

both are incorrect, the correct usage is(for eg: c:/programs/myfiles/cat.txt:

>>> import os
>>> os.path.join('C:/' , 'programs','myfiles','cat.txt') 
'C:/programs/myfiles/cat.txt'
Sign up to request clarification or add additional context in comments.

7 Comments

OP's second version is somewhat correct. Your version is incorrect, and doesn't give the result you posted for me. I assume you didn't run it on Windows.
@interjay as joran beasley said the point of os.path.join is that you don't need to worry about the seperator.
If you ran this then it wasn't on Windows. On Windows your version would give a relative path to the current directory on drive C:, which is incorrect.
The backslash after C: is required on Windows. From the documentation: Note that on Windows, 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.
@BrownieTuffy hmm... so you need c:\\` instead of c:/. I am using linux and it is strongly recommend to use / instead of using `\` you can also use some relative paths.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.