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 ?
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.