Pygame Error : FileNotFoundError: No such file or directory - python

I'm new to programming and just following the steps provided online to make a small game in pygame to learn.
I recently have a problem when I wanted to add an image.
Here is my code.
#sprite
from turtle import Screen
import pygame
import random
import os
WIDTH=500
HEIGHT=600
#遊戲初始化 and 創建視窗
pygame.init()
screen=pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("spacegame")
background_img=pygame.image.load(os.path.join("img","background.png")).convert()
screen.blit(background_img,(0,0))
The trouble come when I run it, and they say :
Traceback (most recent call last):
File "d:\python\test.py", line 13, in <module>
background_img=pygame.image.load(os.path.join("img","background.png")).convert()
FileNotFoundError: No file 'img\background.png' found in working directory 'D:\img'.
PS D:\img>

You are already in the 'img' directory.
So you can use the following line to get the image:
background_img=pygame.image.load("background.png").convert()

It is not enough to put the files in the same directory or sub directory. You also need to set the working directory. A 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 file can be retrieved with __file__. The current working directory can be get by os.getcwd() and can be changed with os.chdir(path).
Put the following at the beginning of your code to set the working directory to the same as the script's directory:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

Related

File not found in working directory pygame

I am attempting to make a simple pygame game, and I need to load in some images. When I run my code, or:
bg_image = pygame.image.load('assets/Fondotiff.tif(1).png').convert_alpha()
It gives me an error which says:
Traceback (most recent call last):
File "C:\Users\victo\Desktop\Assets - Pulga\mainpulga.py", line 12, in <module>
bg_image = pygame.image.load('assets/Fondotiff.tif(1).png').convert_alpha()
FileNotFoundError: No file 'assets/Fondotiff.tif(1).png' found in working directory 'C:\Users\victo\Desktop\Assets - Pulga'.
***Repl Closed***
I have double checked if the image is inside the folder on my desktop and it is there, but for some reason it doesn't find it.
How can I fix this?
The asset file path has to be relative to the current working directory. The working directory is possibly different from the directory of the python file.
It is not enough to put the files in the same directory or sub directory. You also need to set the working directory.
e.g.:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

Run Python file with relative path outside current folder in Jupyter Notebook

Let's say I have the python file ~/file_to_run.py that I want to run from jupyter notebook (~/notebooks/my_notebook.ipynb) using the magic command %run. The problem is that file_to_run.py uses a relative path for example:
open('data/file.csv') # full path ~/data/file.csv
When I run ~/file_to_run.py from ~/notebooks/my_notebook.ipynb with:
%run ../file_to_run.py
I get the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'data/file.csv'
Is the any fix without modifying the python file? Thank you!
Changing the working directory could be a solution:
import os
os.chdir('../') # Change the working directory
%run file_to_run.py # Call the script from new working directory

Error with fonts when using pyinstaller to convert a pygame app to executable

I created a pygame app that has one main python file and an assets folder. I have used pyinstaller to convert the app to an executable file, but every time I receive errors - when I resolve them, different errors come up. I suspect the errors I have been getting recently have to do with the text in my pygame file.
This is the pygame font line I used:
font = pygame.font.SysFont("Arial", 32)
I have tried using .ttf files and copying them into the same folder as my main.py file, but that didn't work either. I also make sure to copy my assets folder into the same folder as the main.app file, but that has not helped either.
I am not sure what this error message is telling me, and there seems to be no other question with this same message (there is no line in my code that is referenced in this error message for me to check).
Fatal Python error: (pygame parachute) Segmentation Fault
Traceback (most recent call last):
File "pygame/pkgdata.py", line 50, in getResource
File "site-packages/pkg_resources/__init__.py", line 1134, in resource_exists
File "site-packages/pkg_resources/__init__.py", line 1404, in has_resource
File "site-packages/pkg_resources/__init__.py", line 1473, in _has
NotImplementedError: Can't perform this operation for unregistered loader type
Any help would be amazing, thank you!
If you use ttf-files, then you need to import them directly instead of using SysFont. So as an example:
size = 12
myfont = pygame.font.Font("Arial.ttf",size)
Arial.ttf also needs to be placed in the same folder where your executable is, or if you have a deeper folder structure, use relative paths (and the folders need to be next to your executable as well):
size = 12
myfont = pygame.font.Font("./myfolder/Arial.ttf",size)
For testing purposes it might also help to use the following command to see from which folder you start, to set your relative path and to know where you are looking for the ttf file:
import os
os.getcwd()

Python on Mac // Changing Working Directory

I have been instructed to change the working working directory. We were provided a file and instructed to put in the Documents folder if we were using a Mac. I cannot seem to to get it work.
from pathlib import Path
import os
Path.cwd()
print(os.getcwd())
os.chdir('/Users/VClark/Documents/cpt180Stuff')
Path.cwd()
print(os.getcwd())
This is the error I am getting:
/Users/VClark/Desktop/CPT 180
Traceback (most recent call last):
File "/Users/VClark/Desktop/CPT 180/workWithFiles.py", line 9, in <module>
os.chdir('Users/VClark/Documents/cpt180Stuff')
FileNotFoundError: [Errno 2] No such file or directory: 'Users/VClark/Documents/cpt180Stuff'
When you are dealing with directories, you must always have a "/" at the beginning of the file path, and at the end, indicating the last word is also a folder, or else it will be treated as a file. And you can't change directories to a file. /Users/hussein/Documents/ is good, Users/hussein/Documents/ and /Users/hussein/Documents are not.

Error with Reading Files

I am working through Learn Python the Hard Way but am having a problem with an exercise that reads a file: https://learnpythonthehardway.org/python3/ex15.html
I have followed this and made sure my file is in the same folder as my python file. I keep getting the error:
Traceback (most recent call last):
File "ex15.py", line 5, in <module>
txt = open(filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ex15_sample.txt'
I am entering: python ex15.py ex15_sample.txt into the powershell. I tried looking up the problem I'm having but could not find anything that helped in my case. Let me know if I am doing something wrong or if I'm missing something. Thanks
You can check your current path and whether your file exists by
import os
#get the current working directory
os.getcwd()
#check whether your file exists in the current working directory
os.path.exists("./ex15.py")
try 2 things below
Check both files .py and .txt are at same location. and then execute program.
this is how i ran the code.
C:\Users\db\Desktop\Python>python ex15.py
enter File Name: ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
If your file is at other location you need to provide absolute path for your file. as
C:\Users\db\Desktop\Python>python C:\Users\deepakb\Desktop\ex15_sample.txt
i had my txt file at desktop this time.
A brief demonstration on working directory and relative file locations..
Say we have a text file named hello.txt with the contents:
Hello World!
that is located at "C:\Users\username\Documents\python\hello.txt"
And we have a python script named script.py with the contents:
with open('hello.txt', 'r') as f:
print(f.read())
Which is located at "C:\Users\username\Documents\python\script.py"
If I just hit the windows key and type power shell and hit enter to open it, I'll see it by default gives me a prompt at my home directory: "C:\Users\username>". From here I can execute my python script by calling C:\Users\username> python C:\Users\username\Documents\python\script.py. If I do this, however, they python interpreter would have started in my home folder, and when it tries to find "hello.txt" it will only search through the folder "C:\Users\username". That's not where the file is, so we get a file not found error.
To resolve this we have a few options. Number one is to re-write our script file to include the full path of our text file: ... open("C:/Users/username/Documents/python/hello.txt", ... This way there is no searching necessary, and the script can be run from anywhere. Another option is to change the working directory of the interpreter from within the script. You can set the working directory with the os library by calling os.chdir('C:/Users/username/Documents/python'). Finally you can set the working directory with PowerShell before calling the python interpreter using the cd command:
C:\Users\username> cd .\Documents\python\
I had the same error.
It was a mistake from me naming the file as ex15_sample.txt.
When you are creating a file in notepad, the file name would be automatically .txt
so if you have created a file just rename it as ex15_sample.
or
You can also run the same program by giving python ex15.py ex15_sample.txt.txt
As you can see the file name might be ex15_sample.txt with a .txt extension.

Categories

Resources