Kanerva Peter
Kanerva Peter

Reputation: 257

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 folder named users, but when I run the program on a linux system, it instead creates, in the root folder, a file named users\userName.txt

How is the path definition different for python 3 in linux?

Upvotes: 0

Views: 13082

Answers (2)

henryJack
henryJack

Reputation: 4624

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('.'))

Upvotes: 2

Matti Lyra
Matti Lyra

Reputation: 13088

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

Upvotes: 0

Related Questions