6

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?

garnertb
  • 9,454
  • 36
  • 38
Romaan
  • 2,645
  • 5
  • 32
  • 63

3 Answers3

19

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"
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
4

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.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
1

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.

pepr
  • 20,112
  • 15
  • 76
  • 139