python change default directory - python

so I recently tried using playsound and the .mp3 is in the same folder as the .py, and it says it could not find the file.
I printed out the current directory and it says it's at C:\Users\me
Shouldn't this be at the same directory as where the .py script is at? This has been happening with my other python scripts where I have to explicitly give it the directory, whereas before I didn't have to and it was just where the python script was at.
Is there a setting for this?

The current directory is defined by where you execute the python file not the location of it. If you want to change the directory you can use the os module:
import os
os.chdir(PATH)

If you're looking for a file in the same directory as the executing python program:
basename = os.path.basename(__file__)
my_file_name = basename + "/myfile"
with open(my_file_name) as my_file:
...
The variable __file__ contains the full pathname of the currently executing Python program.

Related

get the path of the executed file once "compiled" with pyinstaller

I know there are a lot of answers on this subject, but no one works once you compile a script in an executable.
In my python script, I create a file within the same directory of the script.
to get the path of the current dir I use pathlib
basepath = Path(__file__).parent
filename='myfile'
filepath=os.path.join(basepath, filename)
if I print the directory I get the file wrote in the good directory and everything works fine within python
(i.e desktop/myname/myscriptdir/myfile)
but once I "compile" with pyinstaller with --onefile, if I launch the executable, the directory will be
like
/var/folders/nr/w0698dl96j39_fq33lqd8pk80000gn/T/_MEIP12KxC/myfile
believed me, I tried a lot of various method (abspath, os.realpath..)to get the current dir, no one worked fine once in an executable file.
When you compile an app using pyinstaller with the --onefile or -F flag, the file that it creates is actually an archive file, like a .zip file.
When you execute that file it launches a process that extracts itself into a temporary folder somewhere in your OS filesystem. This is the path that is reported when you use the __file__ variable in the compiled application.
It then continues to launch your application from there and the temporary directory becomes the runtime durectory for the duration of the apps life. When the app is finally closed it deletes the temporary runtime directory on it's way out.
Since this is the case there are alternatives.
To get the current working directory during runtime use:
path = '.'
#or
path = os.getcwd()
To get the path to the compiled executable file during runtime:
path = sys.executable

os.getcwd() can't find current working directory

Whenever I try to get current working directory in python on windows with os.getcwd() it shows only the root directory.
for example this directory structure:
root\
ㄴbase\
ㄴㄴfile\
ㄴㄴㄴfile.py\
I use
# files.py
os.getcwd()
output will be:
\---> c:/root\
I want to get c:/root/file
any idea?
thanks in advance
+
actually os.getcwd() finds the 'root:\base\' at some point. but in other cases it doesn't find. so I wanted to know the difference.
Current working directory isn't the path of the script, it's where you are running the script from.
And apparently, you're running your script from c:/root/ directory. If you want the directory of the script use this to get the script path
from os.path import dirname, abspath
script_path = abspath(dirname(__file__))
or run the script from c:/root/base/file to get the path with getcwd().

OS .CWD Skips One DIR how to fix

I am trying to get directory from where script is ran, but os.cwd() skips one dir
Script Path - D:\Mainfolder\Testfolder\testfoldr2\check1.py
But
Output is - D:\Mainfolder\Testfolder
Why no testfolder2 is coming though the script is stored there kindly suggest how to get testfolder2 as working dir
I am Using for checking
import os
print(os.getcwd())
getcwd() will give you your working directory from where you are running the script,
if you want folder of the file then you can use below code:
import os
path = os.path.dirname(__file__)
print(path)

Script writes file in wrong directory

I just experienced a weird behaviour in Python.
I created a copy of a script.py file in a sub-folder within the folder that contains the initial script.
The script at the end exports some data into a .txt file by using:
with open('clayList.2203.txt', 'w',encoding='utf-8') as f:
for item in claysUniqueList:
f.write("%s\n" % item)
The problem is that Python writes the new file on the parent directory instead of the current one.
I checked the path with:
print(sys.path[0])
and it prints the current path correctly.
By default, relative paths are relative to the working directory, that is the directory from which is run the command that run the script.
If you want the path to be relative from the script directory, you will have to explicitly code this behaviour:
import os
filepath = os.path.join(os.path.dirname(__file__), 'clayList.2203.txt')
with open(filepath, 'w',encoding='utf-8') as f:
# ...
When you run code in Visual Studio, there are debugging options.
One of these it the directory to run from, called "Working directory".
(Right click your project and go to settings).
To run from the sub-directory you need to change this.
If you want to start in a sub directory, type that in instead, in the "working directory" shown here:
path for creating the file should be relative to the directory of execution
e.g. your pwd is parent and your script is in parent/child1/child2/script.py then path of the file to be created should be ./child1/child2/clayList.2203.txt

Creating directory on relative path in Python and running in absolute path

I have the following python script (script.py):
#!/usr/bin/env python3
import os
os.makedirs('./downloads/')
Which simply creates a directory named 'downloads' in the directory, where the script.py file is located.
Now I want this program to be run as a cronjob in linux. So the command for that is:
./home/pi/application/script.py
The folder, the program creates should be created under '/home/pi/application/' but it is created in the root directory '/'
How can I fix this?
To get the path where script.py is rather than the path from where you call the script (working directory) you can use:
os.path.dirname(os.path.abspath(__file__))
In you example, the previous command would return /home/pi/application/ (if that is the full path).

Categories