Pygame says it can't find directory - python

# load all images for the players
animation_types = ['Idle', 'Run', 'Jump']
for animation in animation_types:
# reset temporary list of images
temp_list = []
# count number of files in the folder
num_of_frames = len(os.listdir(f'Assets/{self.char_type}/{animation}'))
for i in range(num_of_frames):
img = pygame.image.load(f'Assets/{self.char_type}/{animation}/{i}.png')
img = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale)))
temp_list.append(img)
self.animation_list.append(temp_list)
I am fairly new to python and pygame and am making my first game. I ran into a problem where i'm trying to access files for an animation. For the idle animation the directory is Assets/player/Idle. Inside the folder are 5 images. When I run the code I receive this error:
img = pygame.image.load(f'Assets/{self.char_type}/{animation}/{i}.png')
FileNotFoundError: No such file or directory
I am pretty sure the problem is with the images in the animation folder as I made sure the other folders were found and they were fine. I honestly don't know what to do. If you need the full script then I can send it. Thank you.

I am on a linux system and I had a similar problem. This is what worked for me:
import os
PATH = os.path.dirname(os.path.abspath(__file__))
def get_path(*slices):
return os.path.join(PATH, *slices)
First get the path to the containing directory then in the function return the joined path.
In your case you then need to call:
num_of_frames = len(os.listdir(get_path('Assets', self.char_type, animation))
and
img = pygame.image.load(get_paht('Assets', self.char_type, animation, str(i) + '.png')
other sources of the error:
you are on a windows machine (the path-splitting character on windows is not /)
the files aren't named correctly (0.png, 1.png, 2.png, 3.png, 4.png)
EDIT: Debugging idea: add
print('loading path =', f'Assets/{self.char_type}/{animation}/{i}.png')
before loading the image and check if this file actually exists.

Related

Can't find path to put images in a list?

I'm having some trouble getting my path to work when opening a folder. I put the folder of images into the same folder as the .py file that I'm coding in. Then I try to open it with this code:
images = []
for file in glob('./images/*.PNG'):
print(file)
im = Image.open(file)
images.append(im)
This, however, isn't working. I typed out the "print(file)" so I could see if it was even opening the file and it doesn't seem to even be doing that. I think it's a pathing issue but I have no idea because (as far as I'm concerned) that's the correct path. To reiterate, this "images" directory is in the same directory as the .py file I'm writing in. Any help would be greatly appreciated.
this is usually what I did when I need to access a file inside path:
import os
pathCurrent = os.getcwd() + '\\'
imageFile = pathCurrent + '*.PNG'
And then you can use it as:
images = []
for file in glob(imageFile):
print(file)
im = Image.open(file)
images.append(im)
Let me know if this help.
Maybe:
images = []
def is_img(p: Path) -> bool:
return p.suffix.upper() in ('.PNG', '.JPG', '.JPEG', '.ICO', '.BMP')
for file in glob('./images/*'):
if not is_img(file):
print(file.suffix)
continue
print(file)
im = Image.open(file)
images.append(im)

Include poppler in exe file with pyinstaller

I tried to write a simple program for converting PDF files to JPG. The main idea is a simple .exe file that will find all PDF files in the same directory, and after converting them to JPG put them in the new folder.
And I did it! Using pdf2image, my program doing exactly as I want and as .py and as .exe. But, after running this program on another PC I got an error with popper >following Cmd screenshot
So, I understand, the program tries to find a popper. And sure on another PC program can't find it.
I tried --hidden-import, and --onedir, --onefile e.t.c.
Also saw some similar problem here, as:
PyInstaller and Poppler
Include poppler while generating an application using pyinstaller
But, or I do something wrong, or can't clearly understand how to do solutions in this questions.
What should I do?
#P.S. Maybe, there is a better library or module to create this kind of program?
Whole code:
import os
import pdf2image
from pdf2image import convert_from_path
from inspect import getsourcefile
from pdf2image.exceptions import (
PDFInfoNotInstalledError,
PDFPageCountError,
PDFSyntaxError
)
# Create output direction
# Direction of executable file
script_dir = os.path.abspath(getsourcefile(lambda:0))
# print(script_dir)
output_dir = 'JPG'
# List for files which wasn't converted
error_list = []
# If path don't exist - create
if not os.path.exists(output_dir):
os.makedirs(output_dir)
#print('Path has been created', "\n")
else:
pass
#print('Directory exist', "\n")
# Show all files in directory
file_list = os.listdir()
print(file_list, "List of files")
for file in file_list:
try:
# print(file)
pages = convert_from_path(file, dpi=300, fmt='jpg', output_folder=output_dir, output_file=file)
except Exception as e: print(e)
print("File wasn't converted:", "\n")
if len(error_list) == 0:
print(0, "\n")
else:
for f in error_list:
print(f)
input("Done! Press Enter")

How to move images to a different directory using Linux Ubuntu terminal

I am now trying to build a script that opens, rotates, resizes and saves several images contained in the images directory (running the pwd command gives the message /home/student-01-052f372bc989/images). The images contained in the images directory are of the format TIFF, have a resolution of 192x192 pixel and are rotated 90° anti-clockwise. The script must turn these images in the following formats:
.jpeg format
Image resolution 128x128 pixels
Should be straight
and save the modified images in the /opt/icons directory
Here is the code I currently have:
import os
from PIL import Image
Image_dir = '/home/student-01-052f372bc989/images'
imagedir = os.chdir(Image_dir)
new_dir = '/opt/icons'
for pic in os.listdir(os.getcwd()):
if pic.endswith(".tiff"):
img = Image.open(pic)
new_img = img.resize((128,128)).rotate(270)
newName = pic.replace(".tiff", ".jpeg")
newdir = os.chdir(new_dir)
new_img.save(newName, "JPEG")
imagedir = os.chdir(Image_dir)
The code has no issue when I run it, but when I run the ls /opt/icons command to check if the modified images were copied to the directory, the images are not yet there.
The script is currently located in the /home/student-01-052f372bc989/images directory.
Could someone please tell me what I did wrong?
So... with a bit of digging, i did manage to find an easier way to do the script
the code is as follows:
import os
from PIL import Image
old_path = os.path.expanduser('~') + '/images/'
new_path = '/opt/icons/'
for image in os.listdir(old_path):
if '.' not in image[0]:
img = Image.open(old_path + image)
img.rotate(-90).resize((128, 128)).convert("RGB").save(new_path + image.split('.')[0], 'jpeg')
img.close()

how to solve pygame.error: Couldn't open game\images\person1.png

Can you help me? It's the first time that I use pygame and I found an error loading image. I've just searched in this site for a possible solution, but nothing seems to work for me. I tried to use pygame.image.load() with all the path or with a part, but it didn't work. I created this function that is similar of a function in pygame tutorial in the documentation of pygame.
def load_png(name = ""):
current_path = os.path.dirname(__file__)
game_path = os.path.join(current_path, 'game')
image_path = os.path.join(game_path, 'images')
image_path += "\\" + name
image = pygame.image.load(image_path)
if image.get_alpha() is None:
image = image.convert()
else:
image = image.convert_alpha()
return image, image.get_rect()
The problem was an incorrect file name: "person1.png" instead of "person1.jpg".
If anyone has the same problem, try to print the files in the directory and compare them with the file names in your module.
How do I list all files of a directory?

how to open a folder of images (Python)

I'm working on a program to open a folder full of images, copy the images, and then save the copies of the images in a different directory.
I am using Python 2.4.4, but I am open to upgrading the program to a newer version if that allows me to import PIL or Image because I cannot do that with my version.
As of now, I have:
import Image
import os
def attempt():
path1 = "5-1-15 upload"
path2 = "test"
listing = os.listdir(path1)
for image in listing:
im = Image.open(path1)
im.save(os.path.join(path2))
I am new to Python, so this is probably obviously wrong for numerous reasons.
I mostly need help with opening a folder of images and iterating through the pictures in order to save them somewhere else.
Thanks!
Edit- I've tried this now:
import shutil
def change():
shutil.copy2("5-1-15 upload", "test")
And I am receiving an IOError now: IOError: System.IO.IOException: Access to the path '5-1-15 upload' is denied. ---> System.UnauthorizedAccessException: Access to the path '5-1-15 upload' is denied.
at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in :0
Am I entering the folders wrong? How should I do this if it an a folder within a specific computer network.
Basically there is a folder called images with multiple subfolders within it which I am trying to extract the images from.
Based on this answer, copyfile will do the trick, as you are just copying images from one side to another, as if it was another type of file.
import shutil
import os
def attempt():
path1 = "5-1-15 upload"
path2 = "test"
listing = os.listdir(path1)
for image in listing:
copyfile(image, path2)

Categories