No such file or directory, python, visual studio code - python

grass_img = pygame.image.load('grass.png').convert()
Above script is giving me: No such file or directory. I don't know if it's something with path. Because when I do it in Eclipse it doesn't give an error. I am in visual studio code, grass.png is in the same folder, or if I write the full path from C drive it's still the same error. Really frustrating. I am new. I added my project folder to the path. I really just don't understand path / python path.

Different tools may start script with different Current Working Folder (which you can check with os.getcwd()) and then it searchs your file in different place then you expect.
You could use full path to image but better you should use os.path to get folder with script
BASE = os.path.dirname(os.path.abspath(__file__))
and use os.path to create full path to image
...load( os.path.join(BASE, 'grass.png') )...
BTW:
If you will keep images in subfolder - ie. resources - then you can do
...load( os.path.join(BASE, 'resources', 'grass.png') )...

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

python change default directory

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.

Running Python Code in VS Code and Cannot Find Files in Same Folder

When I try to execute Python files from VS Code, it is unable to find other files in the same folder.
I am running OpenCV code in a test.py file with the following command :
filename = 'image1.png'
img1 = cv2.imread(filename)
print(img1)
The results should show an array of numbers but instead show None because VS Code cannot find image1.png which is in the same folder as the test.py file.
I have searched online for a solution but yet to find a clear one. I suspect I need to manually add this folder to a .json file, but this seems like a clunky solution for every time I need to run files all contained in the same folder.
(I support Monica - StackOverflows needs to stop being aggressive transgender crusaders.)
I think the folder you were at in the terminal is not this folder. If that's the case then use absolute path or path relative from projrct folder instead.
Change the image1.png to ./image1.png should do as well.
If the project folder looks like
projectfolder
|
subfolder
|
main.py
image.png
And the terminal is at projectfolder then relative path of image.png is projectfolder/image.png.
Thogh, use ./image.png is way less troublesome if the picture is always there, but if it's not then absolute path(like /home/user/projectfolder/folder/image.png) will eventually reduce time needed for debug.

Why we need to change our current directory?

If we can directly access and manipulate files in other directories (for example, using the Python code below), when would we need to change our current working directory? What is the advantage of changing the current directory?
import os
print(os.getcwd())
f=open(os.path.join(os.getcwd(),"test_folder")+"\\testfile","w")
f.close()
print(os.getcwd())
os.makedirs("test_folder_2")
print(os.getcwd())
Output:
c:\Users\me
c:\Users\me
c:\Users\me
In the example you're not changing the working directory. You're just getting (printing) it. You do not need to change the working directory. But it's just like you are navigating your files from explorer, to keep your files organised. Sometimes it's done for the file permissions.
The current working directory is the base directory for relative paths. It is the place where you start looking for files and folders, if you don't supply an absolute path. Execute the following script from 2 different directories and examine the difference.
# a.py
import os
print "\tcwd:", os.getcwd()
print "\tpth:", os.path.abspath("a")
Now from a dos box, you get the following output:
C:\Users\user> python a.py
cwd: C:\Users\user
pth: C:\Users\user\a
C:\Users\user> cd ..
C:\Users> python user\a.py
cwd: C:\Users
pth: C:\Users\a
From a different working directory, you target different files with relative paths. It is generally a good idea to use relative paths, because otherwise a script may only work for a single user, or the installation directory of a program must be the same on all computers, which is usually not the case. You must change the working directory to target files and directories correctly with relative paths.

Is it possible to specify the previous directory python?

I am attempting to make a Python testing script module self-contained directory-wise for scalability and maintainability purposes.
I have done some research and haven't been able to find the answer i'm looking for. Basically, I would like to determine if there is a function in Python that can do something similar to cd - in shell.
I would generally like to avoid typing in full path-names, and have all the paths relative to a specified environment.
Example:
I have my main directory where my scripts are located python-scripts, I have folders for each testing environment demo, and a screenshot folder for each testing environment demo-screenshots.
If i wanted to save a screenshot to the screenshot with Python, while working in the demo directory, I would just send it to the directory below: demo-screenshots, using the path '/demo-screenshots/example.png'. The problem is that I don't understand how to move back a directory.
Thank you.
You're looking to change the working directory? The OS module in python has a lot of functions to help with this.
import os
os.chdir( path )
path being ".." to go up one directory. If you need to check where you are before/after a change of directory you can issue the getcwd() command:
mycwd = os.getcwd()
os.chdir("..")
#do stuff in parent directory
os.chdir(mycwd) # go back where you came from
path = os.path.dirname(__file__)
print(path)
will print the CWD of the file, say C:\Users\Test\Documents\CodeRevamp\Joke
path2 = os.path.dirname(path)
print(path2)
will print the Parent directory of of the file: C:\Users\Test\Documents\CodeRevamp

Categories