0

I have a file of images and I want the folder to have a random file selected and that image to be displayed. This is the code I have so far:

dir = path.dirname(__file__)
examQ_dir = path.join(dir, 'Exam Questions')
question = choice(path.join(examQ_dir))

image_surface = pg.display.set_mode((850, 500))
image = pg.image.load(question)

And the error I get is as follows:

Traceback (most recent call last):
  File "D:/A level Comp Sci/Platformer Game in Development Stages/Question.py", line 13, in <module>
    image = pg.image.load(question)
pygame.error: Couldn't open E

And everytime I run it, the last letter of the error is slightly different sometimes it will say

pygame.error: Couldn't open i

And other times there's nothing there at all. I think there's something wrong with my logic of setting this up but I can't work out what. I'm using the PyCharm IDE.

Charlotte
  • 11
  • 2
  • 1
    Note, when you do `question = choice(path.join(examQ_dir))`, then the argument to choice is a string (the file path). You actually select a random letter form the file path. What is a file of images? Do you mean a sprite sheet? See [Spritesheet](https://www.pygame.org/wiki/Spritesheet). – Rabbid76 Feb 11 '20 at 10:54
  • If you want to choose a file randomly from those available in your directory you should first generate a list of possible files, then randomly choose one of those. See: https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory for a good start – Hoog Feb 11 '20 at 12:55
  • 1
    @Hoog The question is not about multiply files in a directory (see deleted answer). The question is about multiple images (sprites) in one bitmap file (sprite sheet). – Rabbid76 Feb 11 '20 at 13:25
  • 1
    @Hoog thank you so much this is exactly the kind of thing I want. – Charlotte Feb 18 '20 at 10:32
  • 1
    @Rabbid76 No I'm not using a spritesheet but this explanation helped me to work out what it was that I was doing wrong about using the choice function so thank you. – Charlotte Feb 18 '20 at 10:33

1 Answers1

0

You have to use os.listdir to get entries in the directory. Use os.isfile to evaluate if an entry is a file:

import os
import random

dir       = os.path.dirname(__file__)
examQ_dir = os.path.join(dir, 'Exam Questions')
allpaths  = [os.path.join(examQ_dir, entry) for entry in os.listdir(examQ_dir)]
filepaths = [p for p in allpaths if os.isfile(p)]

question  = random.choice(filepaths)

Note, when you do question = choice(path.join(examQ_dir)), then the argument to choice is a string (the file path). You actually select a random letter form the file path.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174