Handling path slash character for Windows and Linux compatibility

Windows uses “\\”
Linux uses “/”

Although using the Linux forwardslash will often work on Windows too, its a bit hacky and isn’t guaranteed to work. For correct Python code you should use the pathlib to solve it

from pathlib import Path

    #Use forward slashes with pathlib functions. Path() object will convert forward slashes into the correct kind of slash for the current operating system:
    my_path = Path("some_folder/some_sub_folder/")

    #You can also used the / operator directly in your code to add to a previously created path object:
    my_path = my_path / "some_file.txt"

Detecting Windows or Linux for OS file system dependant path defines

import os


if os.name == 'nt':
    DIRECTORY_FILES_ROOT = 'C:/MyAppDirectory'          #Windows path
else:
    DIRECTORY_FILES_ROOT = '/home/pi/MyAppDirectory'    #Linux path

Referencing files in the project folder

#In project folder:
    Path("myimage.jpg")

#In a sub directory:
    Path("images/myimage.jpg")
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *