0

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?

Filburt
  • 17,626
  • 12
  • 64
  • 115
Kanerva Peter
  • 237
  • 5
  • 13
  • Storing files directly in a home or profile directory is a bad practice, especially on Windows, in which documents belong in [`FOLDERID_Documents`](https://msdn.microsoft.com/en-us/library/dd378457#FOLDERID_Documents). Do not use the default location for this directory relative to the `USERPROFILE` environment variable. A user or administrator can relocate this folder anywhere. Use [`ShGetKnownFolderPath`](https://msdn.microsoft.com/en-us/library/bb762188). – Eryk Sun Feb 17 '18 at 23:49
  • 1
    Possible 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) – jww Feb 18 '18 at 01:17

2 Answers2

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

henryJack
  • 4,220
  • 2
  • 20
  • 24
0

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

Matti Lyra
  • 12,828
  • 8
  • 49
  • 67
  • 1
    On Windows a path starting with a single slash or backslash is a drive-relative path. The OS combines it with the drive or UNC share of the process working directory. Generally this should not be used unless the working directory has been set explicitly. – Eryk Sun Feb 17 '18 at 23:43
  • [How to use “/” (directory separator) in both Linux and Windows in Python?](https://stackoverflow.com/q/16010992/608639) – jww Feb 18 '18 at 01:16