Saying I create a.py under path/to/somewhere/. And later in the IDE(pycharm), I refactor it to path/to/another_place/.
But when I run a.py later, os.getcwd() show its working directory is still in path/to/somewhere. ( os.listdir('.') also show it is in original place.)
The following picture is what I meet , makeimg.py is originally in learn_function
I am new to python and I don't understand how a file/modoule locate itself.
Am I do something wrong? or it is a bug?
os.getcwd() returns the current working directory, it may/may not be the directory in which the your script exists, its the directory from which the script was run. Most probably in your PyCharm Run/Debug configuration you have set the Working directory to path/to/somewhere .
From run/debug configuration doc page for pycharm -
Working directory - Specify a directory to be used by the running task.
When a default run/debug configuration is created by the keyboard shortcut Ctrl+Shift+F10 , or by choosing Run on the context menu of a script, the working directory is the one that contains the executable script. This directory may differ from the project directory.
Ideally your code should not depend on the current working directory , since you can run a python file from anywhere using absolute path to the python file.
Instead if you want the path in which the script resides, use __file__ to get that path in the script.
Example -
print(__file__)
This should print the script's path (as given in sys.argv[0]).
Related
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.
Running print({os.getcwd}) reveals the location where a script is being executed from. In my case, this is happening from outside the directory where my .py and .txt files are saved, which means I have to use absolute paths in order for my code to not return a "FileNotFoundError".
How do I specify the path where python3 scripts are executed in visual studio code, to avoid using absolute paths?
Try
os.chdir(path)
to really change the working directory
or
sys.path.append(path)
to just add another path you can import from.
I have a folder with the following layout:
root/
package0/
__init__.py
main.py
package1/
__init__.py
main.py
Inside the package1/main.pyI have import package0.
When I open a terminal on root folder and run python package1/main.py it works fine. But this is very strange since the cwd was not supposed to be included in path, only the folder in which the script is in, package1 in this case.
When I print the sys.path I can see that the root folder is there.
When I run the same code on my other computer I get a import error as expected.
I cannot understand why I am seeing this behavior.
I have already checked .bashrc and there is no code adding the cwd to the python path.
What might be different on the two computers, I am transferring the root folder from one computer to another through git.
Essentially, whenever you start a particular script, the 'working directory' is the directory from which you started the script. When you run your script from the root folder using command line, the script will look for any files you mention with the root folder as the 'root' of any paths.
Hope that addressed some of your questions. If you're interested in working with changing the starting directory, you can read more about it here.
Edit: Continuation on how to solve changing the working directory for any particular file, this should grab your current running file's directory, change the path to it, and change the directory one higher.
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)
os.chdir("..")
I found a solution. I have no idea of why this solved the problem.
I had two folders added to my pythonpath on .bashrc, some TensorFlow stuff, nothing related to this task.
When I commented the line that added these folders, my cwd stopped to be added to the pythonpath. I took a look into those folders but I could not figure out what was causing this.
I am still curious anyway.
I know that the directory can be automatically changed to that of the current script if we press F5.
But is there a way to automatically do so when I run the codes in interactive mode, or when I open a script? Currently I need to os.chdir() to the current working directory.
Thanks.
You can add the following lines to your script:
import os
os.chdir(os.path.dirname(__file__))
__file__ will return the path of the script, and we can use os.path.dirname to find which directory it is located in. Then just use os.chdir to change to that directory.
I'm new and I have no idea where the default directory for the open() function is.
For example open('whereisthisdirectory.txt','r')
Can someone advise me? I've tried googling it (and looking on stackoverflow) and even putting a random txt file in so many folders but I still can't figure it out. Since I'm beginning, I want to learn immediately rather than type "c:/directory/whatevevr.txt" every time I want to open a file. Thanks!
Ps my python directory has been installed to C:\Python32 and I'm using 3.2
os.getcwd()
Shows the current working directory, that's what open uses for for relative paths.
You can change it with os.chdir.
If you working on Windows OS first type
import os
then type
os.getcwd()
and it should print the current working directory.
The answer is not python-specific. As with programs written in any other language, the default directory is whatever your operating system considers the current working directory. If you start your program from a command prompt window, the CWD will be whatever directory you were in when you ran the program. If you start it from a Windows menu or desktop icon, the CWD is usually defined alongside the program's path when creating the icon, or else falls back to some directory that Windows uses in the absence of that information.
In any case, your program can query the current working directory by calling os.getcwd().
The default location is the CWD (Current Working Directory), so if you have your Python script in c:\directory and run it from there, if you call open() it will attempt to open the file specified in that location.
First, you must import:
import os
Then to print the current working directory:
os.getcwd()
If you want to change the current working directory:
os.chdir('your_complete_required_path')
create the .txt file in the directory where u have kept .py file(CWD) and run the .py file.
The open() function for file always creates files in the current working directory. The best way to find out your current working directory is to find three lines of small code:
import os
current_working_directory = os.getcwd()
print(current_working_directory)
Run this above code and you will get your current working directory where open() function creates a new file. Good Luck!
If you’re running your script through an interpreter (i.e pycharm, VSCode etc) your Python file will be saved, most likely, in my documents (at least in VSCode, in my personal experience) unless you manually save it to a directory of your choosing before you run it. Once it is saved, the interpreter will then use that as you current directory so any saves your Python script will create will also automatically go there unless you state otherwise.
it depends on how you run it from the terminal
like this, it is going to look in your home directory
C:\Users\name>python path\file.py
and like this, it is going to look next to your file
C:\Users\name>cd path
C:\Users\name\path>python file.py