Skip to content Skip to sidebar Skip to footer

What Is The Filepath Difference Between Window And Linux In Python3?

Right now I am creating a text file, and then writing som text to it with the command (in python 3): userFile = open('users\\'+userName+'.txt','w') This creates the file in the f

Solution 1:

It's not different in python 3 in linux it's different in linux. Generally speaking *nix file paths use / as a directory separator, where as windows uses \ (for what ever reason).

In python 3 you can use the pathlib.Path to abstract your code from the OS. So you can do something like

open(Path(f"~/{username}.txt"), "w")

The tilde ~ refers to a user's home directory. Python will figure out which file system the code is running on and do the right thing to map directory separators. You could also do

open(Path(f"/users/{username}.txt"), "w")

to address a specific user directory, the / refers to the root of the file system and should work on Linux and Windows (although I haven't tested that).

https://docs.python.org/3/library/pathlib.html?highlight=pathlib%20path#module-pathlib


Solution 2:

Windows has drives (C:, D:, X: etc) and backslashes or double backslashes, e.g.

C:\Users\JohnSmith is the same as C:\\Users\\JohnSmith

On Linux, there are no drives (per se) and forward slashes, e.g. /home/name

The best way to get a feel for paths is by using os. Try typing this into your python terminal print(os.path.abspath('.'))


Post a Comment for "What Is The Filepath Difference Between Window And Linux In Python3?"