0

I am learning pathlib in Python.

I create a script, printcwd.py:

from pathlib import Path

mypath = Path()

print (mypath.cwd())

This will give me the result I expect if I run the python script by double clicking it inside any folder - it will print the path of that folder as the cwd.

However, if I run the script in my terminal in VSCode (or in powershell) it will always give me the cwd as whatever the current directory of the terminal is set to, rather than the location of the printcwd.py file.

For example, If I placed the file in C:\ and ran it, it would print C:\ as the cwd().

However if I ran it in VSCode with the terminal set to C:\Otherfolder, it would run this:

PS C:\Otherfolder> & C:/Users/name/AppData/Local/Programs/Python/Python39/python.exe C:/printpath.py

and print: C:\Otherfolder, despite the .py file existing at C:\

So, what is happening here ?

Dude
  • 145
  • 1
  • 9

1 Answers1

1

CWD is a property of the terminal, not of the python process. When you double click the file, Windows creates a terminal inside the directory and runs the file. The cwd function just access this property.

If you want to get the directory the file is placed in, use Path(__file__).parent. This access uses the module magic variable that python creates to point to where the file is placed.

MegaIng
  • 7,361
  • 1
  • 22
  • 35
  • Thanks. So say you wanted to create a script which created a bunch of folders in the same directory as the script. To ensure that this always happened, would you write `os.chdir(Path(__file__).parent)` to make sure the cwd was always definitely going to be the same as the file location? – Dude Dec 14 '20 at 12:59
  • 1
    I wouldn't do that. I would just create the folders as children of `Path(__file__).parent`. Without changing `CWD` at all. E.g., create a constant `BASE_DIR` and then use `BASE_DIR / 'a'` to create the Path object for the folder with name `a`. – MegaIng Dec 14 '20 at 13:01
  • OK, as in `BASE_DIR = Path(__file__).parent` ? – Dude Dec 14 '20 at 13:03
  • 1
    Yes. that is what I meant. – MegaIng Dec 14 '20 at 13:04
  • Thanks. Can yo elaborate on why you dont think it would be good practice to modify the cwd? – Dude Dec 14 '20 at 13:04
  • It isn't need, and it might mess with the terminal. In general, try to keep stuff as local as possible. – MegaIng Dec 14 '20 at 13:05