How to find path to current .py file in Spyder (Anaconda)? - python

Set-up
I run a script on my computer, located in the directory Users/path/to/my/script.py.
In the script, I use the path to the script, e.g.,
sub_path = 'Users/path/to/my/'
os.chdir(sub_path + 'other_script/')
As you can see, I define sub_path in the code 'manually'.
Problem
I don't want to define the sub_path manually, I'd rather have Python do it for me.
I'm looking for something similar to the code I use to obtain the current working directory: os.getcwd(), but then a code to obtain the directory of the current file.
I mainly find answers similar to this one, which says,
os.path.abspath(os.path.dirname(__file__))
but in the Spyder & Anaconda set-up, this generates a NameError: name '__file__' is not defined.
What can I do?

You if you want to move back one folder/directory you use the .. in your file path.
os.chdir('../other_scripts/')
will work. You may fine it helpful to view this or the wiki.
If you want to move from where you currently are you can use './new_dir/'. If you want to automate how to find other files you may want to read here which says to use os.walk. This may be the same question.

Mark8888 pointed out to run the whole script (run file (F5)) instead of just pieces of the script
this way multiple approaches should work to get the script file location and change the current working directory
import os
# directory of script file
print(os.path.abspath(os.path.dirname(__file__)))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(__file__)))
# current working directory
print(os.getcwd())
also
import os
import sys
# directory of script file
print(os.path.abspath(os.path.dirname(sys.argv[0])))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))
# current working directory
print(os.getcwd())

I add the following lines to any script I run in case I need to access data relative to the location of the script
import sys
script = sys.argv[0]
print(script)
'C:/SomeFolder/A_Subfolder/CurrentlyRunningScript.py' # changed obviously

First, save your Jupyter Notebook. Second, locate the directory your Jupyter Notebook is stored in. Thirdly, ensure that your Jupyter Notebook and CSV file are in the same place.

Related

Is there a way to load images without using the root file in pygame?

When I load images using pygame, I normally just use file locations such as: 'B:\Python\Images\image.png' but if I want this to be able to run on different computers without needing to edit the code every time, I would just want to go like to do 'image.png' instead. Is there a way to do this? Whenever I try to skip the B:\Python\' part, I get the error: "File Error: No file "image.png" found in working directory 'C:\WINDOWS\System32."
I've seen people use a file location such as: '../Images/image.png' instead but that didn't work (I may have done it wrong).
You have to set the working directory. The resource (image, font, sound, etc.) file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python script. The name and path of the python file can be retrieved with __file__. The current working directory can be set with os.chdir(path).
Put the following at the beginning of your main script to set the working directory to the same as the script's directory. This allows you to specify file paths relative to your main file:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

How do i get the path of the python script i am running in for multiple people

im trying to find out what the path of the file would be to delete it
os.remove(PATHTOFILE)
but im not sure how to get the exact path of the file, the file would be in the same directory as the script but as this script will be on different users in the future im not sure how i would be able to detect that an change the path
import inspect, os
print inspect.getfile(inspect.currentframe()) # file name and path of script
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # directory script is running in
See this answered question
Use sys.argv[0]. You should read it and convert it to an absolute path with os.path.abspath(sys.argv[0]). Do this early, before any code in your Python script calls os.chdir().
Then, you can get the directory part of the script's file name.

Set Working Directory to Notebook Directory

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.

How can I make my Python script a system command and run it easily in any directory in Windows?

I am a Python rookie and I learn Python3.3 in Windows.
I wrote my first script, a script to rename files with incremental filenames. But by now, I had to copy my rename.py script to the directory I want to change the files names and run Python rename.py. It is not a very fancy way to use.
I can improve my code and pass the target directory to run my script in origin directory like Python rename.py .../TargetDir, but I have to copy the directory everytime.
So I want to make my script a system command, then I would only type rename in cmd.exe in the directory I want to rename a bunch of files. How can I approach this.
For this purpose, you'll want to use doskey, which allows you to set aliases for commands.
You use it like this:
doskey macroName=macroDefinition
So you would want to write something like this:
doskey rename=Python rename.py .
Where the . stands for the directory you're currently in. (I wasn't exactly clear on what you wanted -- the way I read your question was that you just want to cd into the directory where you want to rename a bunch of files, then run the script.)
Use sys.argv to get the command line arguments. For example test.py:
import os
import sys
path = sys.argv[1]
print(os.listdir(path))
and then you can create a batch file which should placed in a folder that belongs to the PATH variable. In order to do so, create a text document with the following contents and save it as ListDir.bat. Copy the ListDir.bat to either your python folder, or Windows folder (both should be in your PATH)
ListDir.bat:
python C:\test.py "%CD%"
PAUSE
The %CD% refers to the current directory in the windows prompt. So assuming the python script test.py is in C:\ the first line executes the test.py script with the argument current directory.
I used PAUSE to get user input before completing the script, you could choose not to.
After you save the ListDir.bat file. You can navigate to the folder you want to use it in, and just call ListDir

open() function python default 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

Categories

Resources