1

As in question. Below is code that I use when I have to deal with cross platform paths. Is there better way to do that than this?

import platform

my_os = platform.system()
if my_os == "Windows":
    slash = "\\"
else:
    slash = "/"

Random example in code:

source_path = ""
for part in __file__.split("/")[:-1]:
    source_path += (part + slash)

print(source_path)
Gunnm
  • 974
  • 3
  • 10
  • 21
  • 1
    Use the `os.path` module. There is also `os.sep`. – Martijn Pieters Apr 27 '19 at 09:06
  • duplicate of ['How to use "/" (directory separator) in both Linux and Windows in Python?'](https://stackoverflow.com/questions/16010992/how-to-use-directory-separator-in-both-linux-and-windows-in-python) ? – David Cary Jun 06 '23 at 21:16

2 Answers2

5

The function os.path.join. See the docs for more information: https://docs.python.org/3/library/os.path.html#os.path.join

Ollie
  • 1,641
  • 1
  • 13
  • 31
4

Don't join paths yourself. The standard library comes both with the os.path and pathlib modules, which abstract away (most) platform differences.

For example, getting the current module directory is:

import os.path

source_path = os.path.dirname(os.path.abspath(__file__))

or

import pathlib

source_path = pathlib.Path(__file__).resolve().parent

both of which give you the appropriate absolute path for the current platform.

There is also the os.sep value, which is the main directory separator character for the current platform, as well as os.altsep for platforms such as Windows where multiple path separator characters can be used.

The standard library versions can be relied upon to handle platform-specific edge-cases, such as mixed forward and backward slashes, drive names and UNC paths on Windows.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • While I understand that people that created libraries designed exactly for this task know what they are doing but why it's not recommended to do this yourself? Are there some exceptions that average person doesn't know about? – Gunnm Apr 27 '19 at 09:10
  • 2
    @Gunnm: yes, there are corner cases that most developers forget about, or can get wrong. The standard library versions are broadly tested and cover those edge cases for you, so you don't have to remember them all. – Martijn Pieters Apr 27 '19 at 09:11