Reputation: 2757
I have two strings:
C:\Data
and another folder
Foo1
I need, the windows output to be
C:\Data\Foo1
and the Linux output to be
/data/foo1
assuming /data is in linux. Is there any constant separator that can be used in Python, that makes it easy to use irrespective of underlying OS?
Upvotes: 7
Views: 9660
Reputation: 20752
The os.path.join()
is always better. As Mark Tolonen wrote (my +1 to him), you can use a normal slash also for Windows, and you should prefer this way if you have to write the path explicitly. You should avoid using the backslash for paths in Python at all. Or you would have to double them in strings or you would have to use r'raw strings'
to suppress the backslash interpretation. Otherwise, 'c:\for\a_path\like\this'
actually contains \f
, \a
, and \t
escape sequences that you may not notice in the time of writing... and they may be source of headaches in future.
Upvotes: 1
Reputation: 177481
os.path.normpath() will normalize a path correctly for Linux and Windows. FYI, Windows OS calls can use either slash, but should be displayed to the user normalized.
Upvotes: 4
Reputation: 88977
Yes, python provides os.sep
, which is that character, but for your purpose, the function os.path.join()
is what you are looking for.
>>> os.path.join("data", "foo1")
"data/foo1"
Upvotes: 20