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.
Related
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 using Sublime Text 3 build 3126 on Ubuntu Zesty with the SublimeREPL plugin.
I open a Python REPL with CTRL+SHIFT+P >> SublimeREPL: Python and send a file to REPL with CTRL+, , F and evertyhing works as long as I work on a single Python script file. As soon as I try to move some parts of my code to another module and import it in the main file, I get the nasty ImportError: No module named error.
Trying to open a text file located in the same directory with:
codecs.open('filename', encoding='utf-8')
results in:
IOError: [Errno 2] No such file or directory: 'filename'
Did you investigate whether there was a relation between the file/panel from where you opened SublimeREPL: Python and the output of print os.getcwd()? SublimeREPL initializes its cwd at its startup of the REPL. The cwd will stay for the entire lifetime of the REPL.
As you pointed out, the default cwd for SublimeREPL: Python is:
"cwd": "$file_path"
This means that starting SublimeREPL: Python with your cursor in a blank Sublime panel, results in /opt/sublime_text/ as the cwd. This could be considered undesired and confusing.
However, if you start SublimeREPL: Python while your cursor is in the .py file that you want to run, the REPL will use the folder of your current .py file as its cwd.
Personally I think this is the desired behaviour, but you have to know it before it becomes convenient.
If you change the settings for the cwd to:
"cwd": "$folder",
the above behaviour of the stays unchanged for cases where you're not using sublime-projects. When you do use a sublime-project, the python REPL cwd will be the main project folder, independent of the cursor location at REPL startup. This might be the desired behaviour if you have a python-driven project. However, if you are just using some python scripts in a bigger project, you probably don't want your main project folder to be the cwd in the python REPL.
I spent a full day tearing my hair out while trying to find a solution to this problem.
First I thought there is some problem with $PYTHONPATH. I followed clues given in this (closed) issue on the SublimeREPL GitHub page: https://github.com/wuub/SublimeREPL/issues/355
And while the solution given by the plugin's author didn't work, adding the PYTHONPATH variable containing a path to my working directory to the extend_env key in Packages/SublimeREPL/config/Python/Main.sublime-menu solved the failing imports problem.
I thought I was golden, then I tried to read a text file in Python and got the IOError. Then it finally got to me that the wrong CWD (current working directory) was the culprit.
As the Python docs specify:
"When a module named spam is imported, the interpreter first searches
for a built-in module with that name. If not found, it then searches
for a file named spam.py in a list of directories given by the
variable sys.path. sys.path is initialized from these locations:
the directory containing the input script (or the current directory).
PYTHONPATH (a list of directory names, with the same syntax as the
shell variable PATH). the installation-dependent default.
I tried import os and print os.getcwd() in the REPL promt and surely what I got was:
/opt/sublime_text/
So what I did? The solution was a simple change to a line in Packages/SublimeREPL/config/Python/Main.sublime-menu (in a section corresponding to the REPL I was using). From:
"cwd": "$file_path",
to:
"cwd": "$folder",
Now calling os.getcwd() resulted in a path to the directory containing the file I sent to SublimeREPL and everything worked. Why $file_path gives '/opt/sublime_text' rather than the path to a file is either a question to the plugin's author or some underlying quirk with my system.
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]).
In an IPython nb, is it possible to set programmatically the working directory to the directory of the notebook?
For example, the following code will work in a regular .py file.
import os
# show working dir
os.chdir(os.path.abspath('/'))
print "initial working directory:\t", os.getcwd()
# get path of script file
scriptPath = os.path.abspath(os.path.dirname(__file__))
# change working dir to dir with script file
os.chdir(scriptPath)
# show working directory
print "final working directory:\t", os.getcwd()
However, I can't find the equivalent of the
__file__
variable for a ipython nb file. Is there some equivalent approach for ipynb files?
iPython notebook appears to automatically switch the directory to the same one as the .ipynb file. Do you want to change out of that directory and then change back later? If so, just store the original directory at the start of the program and use it whenever.
import os
orig_dir = os.getcwd()
os.chdir('/some/other/directory')
#do stuff
os.chdir(orig_dir)
EDIT: There appears to be a special variable _dh, which is a list such that _dh[0] contains the name of the directory in which the iPython kernel was started. I only just discovered this, so I'm not sure that this will be robust to a SaveAs either (I can't find a way to do this in my version of iPython). However, it doesn't change when I do os.chdir(), so I suspect that at least the first element of the list always contains the notebook's 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