The Python Oracle

How to use "/" (directory separator) in both Linux and Windows in Python?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence

--

Chapters
00:00 How To Use &Quot;/&Quot; (Directory Separator) In Both Linux And Windows In Python?
00:34 Accepted Answer Score 340
00:56 Answer 2 Score 174
01:11 Answer 3 Score 98
01:17 Answer 4 Score 73
01:41 Answer 5 Score 39
01:53 Thank you

--

Full question
https://stackoverflow.com/questions/1601...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #linux #windows #unix

#avk47



ACCEPTED ANSWER

Score 342


Use os.path.join(). Example: os.path.join(pathfile,"output","log.txt").

In your code that would be: rootTree.write(os.path.join(pathfile,"output","log.txt"))




ANSWER 2

Score 177


Use:

import os
print os.sep

to see how separator looks on a current OS.
In your code you can use:

import os
path = os.path.join('folder_name', 'file_name')



ANSWER 3

Score 98


You can use os.sep:

>>> import os
>>> os.sep
'/'



ANSWER 4

Score 73


os.path.normpath(pathname) should also be mentioned as it converts / path separators into \ separators on Windows. It also collapses redundant uplevel references... i.e., A/B and A/foo/../B and A/./B all become A/B. And if you are Windows, these all become A\B.