Select a random image from a file and display it using pygame - python

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.

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.

Related

os.startfile() don't open the file

I want to make a list of files .max from a directory that the user can choose and then open it when the 3ds Max is not running.
The problem is that I am using os.starfile() to open the .max file and even tryied to use subprocess but none of them works and the following message appears:
"FileNotFoundError: [WinError 2] the system cannot find the file specified:"
As you can you see, the program recognizes the path of the directory and the files .max that are inside of it.
I've already used os.startfile to open a .max file once and it did it works, but can't figure it out why it's not working this time.
import os
import psutil
import easygui
import time
from tkinter import filedialog
from tkinter import *
root = Tk()
msg = "Select a folder to render the .max files inside"
title = "3DS MAX AUTO RENDER"
choice = ["Select Folder"]
reply = easygui.buttonbox(msg, title, choices = choice)
if reply == "Select Folder":
root.directoryPath = filedialog.askdirectory(initialdir="/", title="Select a folder")
print(root.directoryPath)
directoryFiles = os.listdir(root.directoryPath)
print(directoryFiles)
isRunning = "3dsmax.exe" in (i.name() for i in psutil.process_iter())
if (isRunning == False):
for file in directoryFiles:
os.startfile(file)
The file names returned by os.listdir are relative to the directory given. As you are not in that directory when you run the script it can't find the file which is why you get an error.
Use os.path.join to join the directory and file name:
directoryFiles = [os.path.join(root.directoryPath, x) for x in os.listdir(root.directoryPath)]
directoryFiles will then contain the absolute paths so you won't get the error.

Exe file wont launch after converting .py to .exe with pyinstaller

I have a project for minecraft, and after converting it to exe with this command:
pyinstaller "F:\pythonprojetcs\minecraft file mover\splashscreen.py" -F --icon="F:\pythonprojetcs\minecraft file mover\app.ico"
It wont launch. This is the error:
Traceback (most recent call last):
File "splashscreen.py", line 21, in <module>
image = tk.PhotoImage(file=image_file)
File "tkinter\__init__.py", line 4064, in __init__
File "tkinter\__init__.py", line 4009, in __init__
_tkinter.TclError: couldn't open "C:\Users\REINER~1\AppData\Local\Temp\_MEI248722\data\image.png": no such file or directory
[4692] Failed to execute script splashscreen
It works fine when its in the .py format, with to errors.
Its says that tkinter is the error, but I don't understand it.
The code:
# create a splash screen, 80% of display screen size, centered,
# displaying a GIF image with needed info, disappearing after 5 seconds
import os
import tkinter as tk
import shutil
import time
root = tk.Tk()
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
root.geometry('%dx%d+%d+%d' % (width*0.8, height*0.8, width*0.1, height*0.1))
image_file = os.path.dirname(__file__) + '\\data\\image.png'
image = tk.PhotoImage(file=image_file)
canvas = tk.Canvas(root, height=height*0.8, width=width*0.8, bg="brown")
canvas.create_image(width*0.8/2, height*0.8/2, image=image)
canvas.pack()
root.after(2000, root.destroy)
root.mainloop()
print("Világ vagy textúrát akkarsz? (világ = 1 / textúra = 2 / világ másolás = 3 / tutorial = 4)")
choosing = input()
if choosing == "1":
print("\n")
print("\n")
print("Ok, szóval világ.")
print("Hol van?")
original = input()
target = 'C:\\Users\\Refi\\AppData\\Roaming\\.minecraft\\saves'
shutil.move(original,target)
time.sleep(1)
print("Kész!")
print("Ha ezt írja ki: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Reiner Regő\\Downloads\\test', akkor az a fálj nem létezik!")
print("Kérlek várj! Ne zárd be!")
time.sleep(3)
if choosing == "2":
print("\n")
print("\n")
print("Ok, szóval textúra.")
print("Hol van?")
original = input()
target = 'C:\\Users\\Refi\\AppData\\Roaming\\.minecraft\\resourcepacks'
shutil.move(original,target)
time.sleep(1)
print("Kész!")
print("Ha ezt írja ki: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Reiner Regő\\Downloads\\test', akkor az a fálj nem létezik!")
print("Kérlek várj! Ne zárd be!")
time.sleep(3)
if choosing == "3":
print("\n")
print("\n")
print("Ok, szóval világot akarsz másolni.")
print("Mi a neve?")
inputfromuser = input()
original = 'C:\\Users\\Refi\\AppData\\Roaming\\.minecraft\\saves\\' + inputfromuser
target = 'D:'
shutil.move(original,target)
time.sleep(1)
print("Kész! A D:-ben fogod megtlálni!")
print("Ha ezt írja ki: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Refi\\Downloads', akkor az a fálj nem létezik!")
print("Kérlek várj! Ne zárd be!")
time.sleep(3)
print('\n')
input("nyomd meg az entert a kilépéshez")
This copies files from one diretory from another, the splashscreen code is just an example.
Please help!
Your script is trying to access image files from a directory relative to the script itself; this works when the script is installed unpacked, with resources actually on the file system. But when bundled into an executable, that can't work; the image isn't going to be there unless you've copied it in with the executable (an ugly hack of a solution); you need to bundle it into the executable itself in such a way that it can be extracted at runtime by your script.
You need to read the docs on spec files, specifically, adding data files (to bundle the data with the executable when you build it) and using data files from a module (to extract the bundled data in memory at runtime).
You'll only have access to the data from the file, it won't be a file on disk anymore, so you'll need to use alternate means of loading, e.g. from base64 encoded data.

FileNotFoundError: [Errno 2] - Possible work network issue?

I am trying to read content of a file on my work network from my work network. I copy and pasted a code snippet from a google search and modified it to the below. Why might I still be getting [Errno 2] (I have changed some of the path names for this question board)
The file path in my file explorer shows that "> This PC > word common common" and I don't have "This PC" in my path. I tried adding that into the place I would think it goes in the string. That didn't solve it.
I tried making sure I have matching capitalization. That didn't solve it.
I tried renaming the file to have a *.txt on the end. That didn't solve it.
I tried the different variations of // and / and \ with and without the r predecessor and while that did eliminate the first error I was getting. It didn't help this error.
(Looking at the code errors in the right gutter is says my line length is greater than the PEP8 standard. While I doubt that is the root of my problem, if you can throw in the 'right' wrap method for a file path that long that would be helpful.)
myfile = open("z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246", "rt") # open lorem.txt for reading text
contents = myfile.read() # read the entire file into a string
myfile.close() # close the file
print(contents) # print contents
Full Error Copy:
C:\Users\e087680\PycharmProjects\FailureCompiling\venv\Scripts\python.exe C:/Users/e087680/PycharmProjects/FailureCompiling/FirstScriptAttempt.py
Traceback (most recent call last):
File "C:/Users/e087680/PycharmProjects/FailureCompiling/FirstScriptAttempt.py", line 1, in
myfile = open("z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246", "rt") # open lorem.txt for reading text
FileNotFoundError: [Errno 2] No such file or directory: 'z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246'
EDIT
DEBUG EFFORTS
working to figure out how to change directory. Just in case that is the problem. Tested this code bit
import os
path = "z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246"
os.chdir(path)
isExist = os.path.exists(path)
print(isExist)
Received this error
C:\Users\e087680\PycharmProjects\FailureCompiling\venv\Scripts\python.exe C:/Users/e087680/PycharmProjects/FailureCompiling/ScriptDebugJunkFile.py
Traceback (most recent call last):
File "C:/Users/e087680/PycharmProjects/FailureCompiling/ScriptDebugJunkFile.py", line 5, in <module>
os.chdir(path)
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246'
My intention for adding the picture below is to show how File Explorer displays the file path for my file
FileExplorerPathScreenShot
EDIT
I think this confirms that my 'OS' doesn't have my file.
from os import path
path.exists("PCC_ESS_FC_Full_Report_65000122-1_R0016_962019_9246")
def main():
print ("File exists:" + str(path.exists('PCC_ESS_FC_Full_Report_65000122-1_R0016_962019_9246')))
if __name__== "__main__":
main()
Output
File exists: False
I thought OS was a standard variable for Operating system. Now I'm not sure.
EDIT
Using Cmd in DOS, I confirmed that my path for the z: is correct
EDIT - Success
I ran
import os
print( os.listdir("z:/"))
Confirmed I don't need the monster string of folders.
Confirmed, although explorer doesn't show it, it is a *.txt file
Once I implemented these two items the first code worked fine.
Thank you #Furas
To open and read a file specify the filename in your path:
myfile = open("U:/matrix_neo/word common common/hello world.txt", "rt") # open file
contents = myfile.read() # read the entire file into a string
myfile.close() # close the file
print(contents) # print contents
The U: is a mapped drive in my network.
I did not find any issue with your change dir example. I used a path on my U: path again and it returned True.
import os
path = "U:/matrix_neo/word common common"
os.chdir(path)
isExist = os.path.exists(path)
print(isExist)
The check the attributes on the directory that you are trying to read from. Also try to copy the file to a local drive for a test and see if you can read the file and also check if it exists.
This is an alternative to the above and uses your path to make sure that the long file path works:
import os
mypath = "z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246"
myfile = 'whatever is your filename.txt'
if not os.path.isdir(mypath):
os.makedirs (mypath)
file_path = os.path.join(mypath, myfile)
print(file_path)
if os.path.exists(file_path) is True:
with open(file_path) as filein:
contents = filein.read()
print(contents)
I tested this code using a long csv file.,Replace the variable myfile with whatever is your file name.

Use a raw_input to specify a specific file to create a copy of it's back up and change the file names of the back up and original file

I am working to set up a process that creates a new file from a backup file that is already in a folder. My program currently works, but I would like to eliminate as much of the user input as possible, so that all you have to do is enter the filename that just crashed on you and watch the program do the rest. I am fairly new at python and have been having trouble figuring out a way to get that initial raw_input to be the basis for the rest of the program to run off. I have uploaded the code that I have which currently does the job, so any tips that would help me make this code better would be much appreciated.
Thanks!
import os
import copy
import shutil
def copy_vrb():
#Creates a copy of a specific "Filename.vrb" which gets renamed to "Filename_COPY.vrb"
oldvrb=raw_input("Enter the .vr filename you were working on before it crashed: ") # With file extension
newvrb=raw_input("Rename the new .vrb file to Filename_COPY")
shutil.copy(oldvrb, newvrb + ".vrb") # Without file extension
copy_vrb()
def file_rename():
# Takes original "Filename.vr" that crashed, and changes the filename to "Filename_BAD.vr".
oldname=raw_input("Enter the Filename.vr that you were working on before it crashed: ") # With file extension
newname=raw_input("Rename the file as Filename_BAD")
os.rename(oldname, newname + ".vr")
file_rename()
def rename_copy():
# Renames Filename_COPY.vrb to Filename_NEW.vr
oldname=raw_input("Enter the Filename_COPY.vrb: ") # With file extension
newname=raw_input("Rename to Filename_NEW: ") # Without file extension
os.rename(oldname, newname, +".vr")
rename_copy()
In my data folder that I would work out of, I have multiple pairs of files, (10001.vr(the file that would crash), and 10001.vrb(the backup that is created when I open the file in VR Mapping) What I want is to be able to input the specific file that crashed.
Create a copy of the 10001.vrb file ---> 10001_COPY.vrb
Change the 10001.vr file ---> 10001_BAD.vr
Lastly change the 10001_COPY.vrb file into the new usable file ---> 10001_NEW.vr
One way of doing this is you accept the name of file as a command line input instead of doing raw_input().
https://www.pythonforbeginners.com/system/python-sys-argv
import os
import copy
import shutil
def copy_vrb(oldvrb):
newvrb = os.path.splitext(oldvrb)[0] + "_COPY"
shutil.copy(oldvrb, newvrb + ".vrb") # Without file extension
oldvrb=raw_input("Enter the .vr filename you were working on before it crashed: ")
copy_vrb(oldvrb)
And then you do the rest for the other functions.
You're on the right track. Just a matter of merging your functions - perhaps:
import os
import shutil
def recover_vrb():
vr_file = raw_input("Enter the .vr filename you were working on before it crashed: ") # With file extension
vr_name = vr_file.split('.')[0]
vrb_file = vr_name + '.vrb'
moved_vr_file = vr_name + '_BAD.vr'
os.rename(vr_file, moved_vr_file)
shutil.copy(vrb_file, vr_file)

Python - IO:Error Cannot Identify Image File

I'm working on an image to text OCR system and I kept receiving an error on the console stating
Traceback (most recent call last):
File "crack_test.py", line 48, in <module>
temp.append(buildvector(Image.open("./iconset/%s/%s"%(letter,img))))
File "/Users/seng_kin/anaconda/lib/python2.7/site-packages/PIL/Image.py", line 2290, in open
% (filename if filename else fp))
IOError: cannot identify image file './characterset/a/.DS_Store'
I have a folder in a ../OCR/characterset/ directory which has 26 subfolders representing 26 characters whereby each subfolder contains a .PNG of a character.
The score_test.py is stored in ../OCR/
score_test.py Code:
from PIL import Image
import os, sys
import math
****def functions****
iconset = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z']
imageset = []
for letter in iconset:
for img in os.listdir('./characterset/%s/'%(letter)):
temp = []
if img != "Thumbs.db": #windows check...
temp.append(buildvector(Image.open("./characterset/%s/%s"%(letter, img))))
imageset.append({letter:temp})
I saw other solutions on the website but all is related to the absence of from PIL import Image. Am I missing something?
.DS_Store is a "hidden" file in directories on Mac OS X.
In your if img != "Thumbs.db" check, you should add:
if not img.startswith('.') and img != 'Thumbs.db':
this way you filter out all "hidden" files.

Categories

Resources