FileNotFoundError: No such file or directory in pygame [duplicate] - python-3.x

This question already has an answer here:
Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."
(1 answer)
Closed 2 years ago.
I am somewhat new to programming, I don't like it that much but as it is school work I have to do it, good thing I find it interesting.
Here is my code, note I'm using VS code (some things are in french but that shouldn't affect anything):
import pygame
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Space vaders")
fond = pygame.image.load (testingfield.png)
and I get:
Traceback (most recent call last):
File "c:/Users/faver/Desktop/Space_Invaders-NSI/space_invaders_1.py", line 11, in <module>
fond = pygame.image.load ('testingfield.png')
FileNotFoundError: No such file or directory.
the file is indeed in the folder, and if I put fond = pygame.image.load ((r'C:\Users\faver\Desktop\Space_Invaders-NSI\testingfield.png'))it works perfectly, the problem now is that it'd be hard to actually send it since the other person would lack the folders I place there.
I've also tried import os a = os.path.lexists("/Users/suyeon/Documents/pythonWorkspace/pygame_basic/character.png") print(a) and it returned false, so I'm pretty much confused, I'd appreciate help if possible ^^'

The image file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd() and can be changed by os.chdir(path).
One solution is to change the working directory:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
An alternative solution is to find the absolute path.
If the image is relative to the folder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()) the image filename. e.g.:
import pygame
import os
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
# [...]
# join the filepath and the filename
fondImgPath = os.path.join(sourceFileDir, 'testingfield.png')
fond = pygame.image.load(fondImgPath)

Related

Python FileNotFoundError even if the File is there

My project directory tree is something like this,
build
----fonts
--------Roboto Bold.ttf
----main.py
The following code errors out,
from pyglet import font
font.add_file("fonts\\Roboto Bold.ttf")
Also tried this code,
import os
from pyglet import font
font.add_file(str(os.getcwd())+"\\fonts\\Roboto Bold.ttf")
the error is,
Traceback (most recent call last):
File "{full_dir_name}\build\main.py", line 25, in <module>
font.add_file(str(os.getcwd())+'\\fonts\\Roboto Bold.ttf')
File "C:\python-3.8.5-amd64\lib\site-packages\pyglet\font\__init__.py", line 183, in add_file
font = open(font, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '{full_dir_name}\\fonts\\Roboto Bold.ttf'
I have tried about a day now and also seen other posts here but could not resolve...
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 file.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd(). If the file is in an subfolder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()) the relative filepath. e.g.:
font.add_file(str(os.getcwd())+"\\fonts\\Roboto Bold.ttf")
font.add_file(os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts/Roboto Bold.ttf"))

Can't open and import files on Python

I just started learning Python this month with no prior coding knowledge. Before I could even get to practice coding, I was stuck with opening & importing files! To this end, I have no idea how to fix the problems as a newbie, so I will try to explain as best as I can.
1. Opening files.
Working directory is correct. The csv file was created with Geany on the Ubuntu operating system.
name=[]
age=[]
height=[]
with open(’/home/stephanie/chapter5exercise.csv’, encoding=’utf-8’,mode=’r’,newline=’’) as
csv file:
reader = csv.reader(csvfile, delimiter=’,’)
for row in reader:
name.append(row[0])
age.append(row[1])
height.append(row[2])
print("Done!")
**Error message:**
File "<ipython-input-3-f801fef0d65e>", line 5
with open(’/home/stephanie/chapter5exercise.csv’, encoding=’utf-8’,mode=’r’,newline=’’) as
^
SyntaxError: invalid character in identifier
2. Importing files
I downloaded a whatsapp chat text file for a coding exercise. It is stored in my Desktop environment. However, when I attempted to import it on Jupyter Notbook it didn't work.
I believe this is the problem, although I do not know how to work-around this:
the txt file's location as shown in my terminal:
/Users/Mac/Desktop
while the working directory as shown on Jupyter is:
/home/stephanie/Desktop
with open ("_chat.txt") as f:
data = f.readlines()
**error message:**
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-5-07cb5c381c47> in <module>
----> 1 with open ("_chat.txt") as f:
2 data = f.readlines()
FileNotFoundError: [Errno 2] No such file or directory: '_chat.txt'```
Any input or advice is greatly appreciated. Thanks very much in advance!
For the first error, try changing the apostrophes in the open line. For example, change ’/home/stephanie/chapter5exercise.csv’ to '/home/stephanie/chapter5exercise.csv'.
Apparently, the apostrophe (’) that you are using is not the correct one.
For the second error, try giving the entire path of the txt file.

Programmatically import Python files as modules within another Python file and run them

There's a highly upvoted StackOverflow thread which says that the best way to run Python files within another Python file is to import them as a module.
That works well for me, except that I'm having trouble doing it programmatically in a case where there are at least hundreds (if not thousands) of files to be run.
All of the files are in the same directory and share a common naming convention. I tried to run them like this:
import glob, os
for filename in glob.glob("*_decomp*"):
import filename
but that throws an error:
Traceback (most recent call last):
File "C:\Python35\lib\site-packages\IPython\core\interactiveshell.py", line
3066, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 4, in
import filename
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.1.3\helpers\pydev_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
ImportError: No module named 'filename'
The variable filename is also underlined in red in the IDE, which negates my original hypothesis that it was simply a matter of needing to remove the .py file extension.
This works fine for printing:
import glob, os
for filename in glob.glob("*_decomp*"):
# import filename
print(filename)
So I'm not really sure what the problem with the earlier statement is or how to work around it. I can also do the import manually and that works fine, but again I'd like to do it programmatically so that I don't have to type all of the file names and because the file names will change over time.
Finally, I also tried it with [:-3] (i.e. filename[:-3]) to remove the file extension, but again that only works for print() and not import.
There are other ways of importing not covered by the SO link you give, for example (although I'm not holding this up as a canonical or even necessarily good way of importing, but it works for me) based on one of the examples I found via this SO question/answers Building a minimal plugin architecture in Python I wrote a simple plugin implementation below - it searches a folder called 'plugins' below wherever the .py file with this in it is. Each plugin has to implement a class called Plugin, they all get the same parameters.
path = 'plugins'
# find subdirs of the path - these are the groups
# for each group, load all the .py files, each provides one or more actions
searchdir = os.path.join(os.path.split(__file__)[0],path)
if os.access(searchdir, os.F_OK):
print "searchdir=",searchdir
print "results=",os.walk(searchdir)
(root, dirs, files) =os.walk(searchdir).next()
print root,dirs,files
for dir in dirs:
print "scanning dir",dir
self.groups[dir] = []
sys.path.insert(0, os.path.join(root,dir))
for f in sorted(os.listdir(os.path.join(root,dir))):
print "looking at",f
fname, ext = os.path.splitext(f)
if ext == '.py':
print "importing ",f
mod = __import__(fname)
try:
self.groups[dir].append(mod.PlugIn(group,cmdobj,config, jts_data, directives, current_config_props,allcomponents,globals))
except:
print "URGH! plugin instantiation error!"
raise
sys.path.pop(0)
else:
print "############# no plugins folder",searchdir

Python idle not opening text file with open ()

being a few weeks old coder,I am unable to make python read my file despite the code and .txt file being in the same folder
highest_score=0
result_f = open("results.text")
for line in result_f:
if float (line)>highest_score:
highest_score = float(line)
result_f.close()
print("the highest score:")
print(highest_score)
and result is
Traceback (most recent call last):
File "C:\Python33\-mu.py", line 2, in <module>
result_f = open("results.text")
FileNotFoundError: [Errno 2] No such file or directory: 'results.text'
Please help
Basically you are trying to open the file result.text. The error returned is that Python Idle cannot find that file. I notice that you mentioned a .txt file but in your code you try to open a .text file.
So I would suggest you to check wheter your file extension is .txt or .text and, in case, correct.
If the error still persists, try to give the full path to the open command. For example:
result_f = open("/Users/Joe/Desktop/results.text")
Both Windows and Mac OS give, somewhere when right-clicking on the file, the full path (among other information).
I faced a similar issue, where I was trying to read a file in idle but it couldn't find the path. What worked for me:
Enter the full path of the file with the extension
Instead of the native path writing style in windows i.e. (D:\python\sample.txt)
use (D:/python/sample.txt)
It worked out for me in Windows 7, IDLE 3.6.4 and also works on Windows 8

Cx_Freeze compiled pygame file doesn't work

The following error happens if i try to compile my python (using python 3.2) file:
Traceback(most recent call last):
File
"c:\python32\lib\site-packages\cx_Freeze\initscripts\Console3.py", line
27, in <module>
exec(code, m.__dict__)
File "Abertura.py", line 208, in <module>
File "Abertura.py", line 154, in main
File "Abertura.py", line 9, in __init__
pygame.error: Couldn't open
C:\Python32\build\exe.win32-3.2\library.zip\Imagens\menu1.png
I already included pygame._view and tried to copy the 'Imagens' directory to the library.zip file, but it doesn't work. I'm using images, musics and videos that come's from other directories by including in my code:
def file_path(filename, directory):
return os.path.join(
os.path.dirname(os.path.abspath(__file__)),
directory,
filename
)
And this is my setup.py file:
from cx_Freeze import setup, Executable
exe=Executable(
script="Abertura.py",
base="Win32Gui",
)
includefiles=[('C:\Python32\Imagens', 'Imagens'),
('C:\Python32\Musicas','Musicas'),
('C:\Python32\Videos','Videos')
]
includes=[]
excludes=[]
packages=[]
setup(
version = "1.0",
description = "RPG",
author = "Pedro Forli e Ivan Veronezzi",
name = "Batalha Inapropriada",
options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
executables = [exe]
)
How do i fix it?
(sorry about my possibles english mistakes)
Anything accessed from within a compressed archive (such as zips, rars, tar.gzs, etc...) need to be decompressed first before you access them.
That being said, you should not have your recourse files in a zip because decompressing it every time to want to access something is slow, and difficult. Your resource files should be in a normal directory, not an archive.
The reason why you're getting this error is because it's looking for a folder named library.zip and it's not finding one because library.zip is not a folder, it's a file.
How I would suggest to combat this error is to extract everything into a folder named library and to change in your code anywhere that library.zip exists to library.

Resources