I am making a game, and I need to load some password protected audio files from a .zip file, but I get this error:
io.UnsupportedOperation: seek
io.UnsupportedOperation: seek
io.UnsupportedOperation: seek
b'hey you did it!' #THIS IS FROM THE PROGRAM
Traceback (most recent call last):
File "C:\Python36\lib\zipfile.py", line 849, in read
data = self._read1(n)
File "C:\Python36\lib\zipfile.py", line 917, in _read1
data += self._read2(n - len(data))
File "C:\Python36\lib\zipfile.py", line 949, in _read2
data = self._fileobj.read(n)
File "C:\Python36\lib\zipfile.py", line 705, in read
self._file.seek(self._pos)
AttributeError: 'NoneType' object has no attribute 'seek'
And this is my code below:
from zipfile import ZipFile
from PIL import Image
from io import BytesIO
import pygame
from pygame.locals import *
import pyganim
import sys
pygame.init()
root = pygame.display.set_mode((320, 240), 0, 32)
pygame.display.set_caption('image load test')
#THIS IS HOW TO LOAD IMAGES (WORKS)
with ZipFile("spam.zip", 'r') as archive:
mcimg = archive.read('a.png', pwd=b'onlyforthedev')
mc = pygame.image.load(BytesIO(mcimg))
anime = pyganim.PygAnimation([(mc, 100),
(mc, 100)])
anime.play()
#THIS IS HOW TO LOAD MUSIC (DOES NOT WORK)
with ZipFile('spam.zip') as zippie:
with zippie.open('zora.mp3', pwd=b'onlyforthedev') as zora:
pygame.mixer.music.load(zora)
pygame.mixer.music.play(-1)
#THIS IS HOW TO LOAD TEXT (WORKS)
with ZipFile('spam.zip') as myzip:
with myzip.open('eggs.txt', pwd=b'onlyforthedev') as myfile:
print(myfile.read())
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
root.fill((100, 50, 50))
anime.blit(root, (100, 50))
pygame.display.update()
What can I do to load sound files without raising such an error? And what is 'seek'?
I also get this error on python 3.6.
I am going to guess that pygame.mixer.music.load calls the seek method on zippie, which is a ZipExtFile.
From python 3.7 ZipExtFile objects now have a seek method. I think that if you upgrade to python 3.7.2 or newer, then your error should go away.
Try to replace
pygame.mixer.music.load(zora)
with
with BytesIO(zora.read()) as zora_bio:
pygame.mixer.music.load(zora_bio)
This worked for me on python 3.6 with h5py.File().
I'm guessing it's the same problem as with pygame..load().
EDIT:
I now realize the above solution already exists in your code when you LOAD IMAGES:
with ZipFile("spam.zip", 'r') as archive:
mcimg = archive.read('a.png', pwd=b'onlyforthedev')
mc = pygame.image.load(BytesIO(mcimg))
So for uniformity, you could LOAD MUSIC in a similar way:
with ZipFile('spam.zip') as zippie:
zora = zippie.read('zora.mp3', pwd=b'onlyforthedev')
pygame.mixer.music.load(BytesIO(zora))
Related
I wrote a small Python script which takes all .jpeg img-files from a given "./Input" folder, creates a thumbnail from these images and saves them in a "./Output" file. It works perfectly fine when executed in an IDEA (In my case PyCharm), but when I created the executable with pyinstaller and tried to execute it, the following error appeared:
Traceback (most recent call last):
File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'
[84693] Failed to execute script 'image_resizer' due to unhandled exception: No module named 'PIL'
[84693] Traceback:
Traceback (most recent call last):
File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
Here is my code:
import shutil
from PIL import Image
import glob, os
import time
output_directory = "./Output"
def photo_picker():
pictures = []
try:
for filename in glob.iglob("./Input/*.jpg"):
pictures.append(filename)
except FileNotFoundError:
print("could not execute")
return pictures
def create_output_folder():
if os.path.exists(output_directory):
shutil.rmtree(output_directory)
try:
os.mkdir(path=output_directory, mode=777)
except FileExistsError:
print("Could not execute")
def crop_image(img, new_name):
size = (2000, 2000)
with Image.open(img) as im:
im.thumbnail(size)
print(im.info)
img_name = f"{new_name}"
im.save(output_directory + "/" + img_name, "JPEG")
def main():
photos = photo_picker()
create_output_folder()
time.sleep(2)
for f in photos:
img_name_splitted = f.split("/")
img_name = img_name_splitted[len(img_name_splitted) - 1]
print(img_name)
crop_image(f, img_name)
return 0
if __name__ == "__main__":
main()
I installed the module Pillow, uninstalled it ,tried to install PIL (which didn't work). But as I mentioned before, when executing it in an IDEA it works.
Goal : 1.Select PDF 2.OCR PDF 3.Write tabels to excel with onefile .exe
Script is working in Pycharm perfect but after compiling to exe i am getting this traceback.
Traceback (most recent call last):
File "OCR_Menu.py", line 26, in <module>
File "ocrmypdf\api.py", line 340, in ocr
File "ocrmypdf\_validation.py", line 240, in check_options
AttributeError: 'NoneType' object has no attribute 'languages'
[11220] Failed to execute script 'OCR_Menu' due to unhandled exception!
Any help to get this script working as a single executable file will be very appreciated!
Thank you!
import ocrmypdf
import camelot
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)
# if filename is not None:
if __name__ == '__main__': # To ensure correct behavior on Windows and macOS
ocrmypdf.ocr (filename, 'output.pdf', deskew=True,)
file = "output.pdf"
tables = camelot.read_pdf(file, pages = "1-end", flavor='stream')
print(tables.n)
tables=camelot.read_pdf(file, pages='1-end', flavor='stream')
tables.export(filename + ".xlsx", f='excel')
if you're currently using googletrans==3.0.0, please switch to googletrans==3.1.0a0 for the temporary fix.
I am trying the gTTS (Google Text To Speach) function in python, saving the mp3 file works (the file is being saved and can be played).
Now I am trying to play the file directly with the below code, but it is throwing an error
Code:
import gtts
import pyglet
import os
import time
text = ("Hello World")
obj = gtts.gTTS(text=text, lang='en')
speech_filename = 'c:/test_voice.mp3'
obj.save(speech_filename)
print("Play sound...")
music = pyglet.media.load(speech_filename, streaming=False)
music.play
sleep.time(music.duration) #prevent from killing
os.remove(speech_filename) #remove temp file
Error:
Traceback (most recent call last):
File "C:\python\text-to-speach.py", line 16, in
music = pyglet.media.load(speech_filename, streaming=False)
File "C:\Python\lib\site-packages\pyglet\media\sources\loader.py", line 63, in load
source = get_source_loader().load(filename, file)
File "C:\Python\lib\site-packages\pyglet\media\sources\loader.py", line 84, in load
return WaveSource(filename, file)
File "C:\Python\lib\site-packages\pyglet\media\sources\riff.py", line 200, in init
'AVbin is required to decode compressed media')
pyglet.media.sources.riff.WAVEFormatException: AVbin is required to decode compressed media
it is looking for AVbin,
check following would help you
https://stackoverflow.com/questions/10302873/python-pyglet-avbin-how-to-install-avbin
Ok so this is how I solved it, I also added a delay loop that waits for the audio file to finish and delete it afterwards.
import gtts
import pygame
#install pyglet and install http://avbin.github.io/AVbin/Download.html
#extract the avbin.dll from windows/system32/ folder to windows/system/ folder
import os
import time
pygame.mixer.init()
text = ("Hello, World")
obj = gtts.gTTS(text=text, lang='en')
speech_filename = "c:/python/code/test_voice.mp3"
obj.save(speech_filename)
print("Play sound...")
pygame.mixer.music.load(speech_filename)
pygame.mixer.music.play()
busy = True
while busy == True:
if pygame.mixer.music.get_busy() == False:
busy = False
pygame.quit()
os.remove(speech_filename) #remove temp file - remove line to keep file
I have images in the same directory with a python file, i am trying to loop over the images and convert them into base64 but am getting this error.
Am using Ubuntu 14.0.4
Traceback (most recent call last):
File "convert_to_base64.py", line 33, in <module>
print(main())
File "convert_to_base64.py", line 26, in main
convert_to_base64()
File "convert_to_base64.py", line 19, in convert_to_base64
with open("*.jpg", "rb") as f:
IOError: [Errno 2] No such file or directory: '*.jpg'
Here is my python code
# -*- coding: utf-8 -*-
import os
import sys
import xlrd
import base64
import urllib
from datetime import datetime
reload(sys) # to re-enable sys.setdefaultencoding()
sys.setdefaultencoding('utf-8')
def convert_to_base64():
"""
Read all jpg images in a folder,
and print them in base64
"""
with open("*.jpg", "rb") as f:
data = base64.b64decode(f.read())
print data
def main():
start_datetime = datetime.now()
convert_to_base64()
end_datetime = datetime.now()
print '------------------------------------------------------'
print 'Script started : {}'.format(start_datetime)
print 'Script finished: {}'.format(end_datetime)
if __name__ == '__main__':
print(main())
print('Done')
someone help me figure out what am doing wrong.
Thanks
This is how I looped for images in a directory:
import os
pictures = []
for file in os.listdir("pictures"):
if file[-3:].lower() in ["png"]:
pictures.append(file)
Please refer to Python documentation https://docs.python.org/2/tutorial/inputoutput.html for more info on open() function:
open() returns a file object, and is most commonly used with two arguments: open(filename, mode).
I'm trying to write a simple script to merge two PDFs but have run into an issue when trying to save the output to disk. My code is
from PyPDF2 import PdfFileWriter, PdfFileReader
import tkinter as tk
from tkinter import filedialog
### Prompt the user for the 2 files to use via GUI ###
root = tk.Tk()
root.update()
file_path1 = tk.filedialog.askopenfilename(
filetypes=[("PDF files", "*.pdf")],
)
file_path2 = tk.filedialog.askopenfilename(
filetypes=[("PDF files", "*.pdf")],
)
###Function to combine PDFs###
output = PdfFileWriter()
def append_pdf_2_output(file_handler):
for page in range(file_handler.numPages):
output.addPage(file_handler.getPage(page))
#Actually combine the 2 PDFs###
append_pdf_2_output(PdfFileReader(open(file_path1, "rb")))
append_pdf_2_output(PdfFileReader(open(file_path2, "rb")))
###Prompt the user for the file save###
output_name = tk.filedialog.asksaveasfile(
defaultextension='pdf')
###Write the output to disk###
output.write(output_name)
output.close
The problem is that I get an error of
UserWarning: File to write to is not in binary mode. It may not be written to correctly. [pdf.py:453] Traceback (most recent call last): File "Combine2Pdfs.py", line 44, in output.write(output_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PyPDF2/pdf.py", line 487, in write stream.write(self.header + b("\n")) TypeError: write() argument must be str, not bytes
Where have I gone wrong?
I got it by adding mode = 'wb' to tk.filedialog.asksaveasfile. Now it's
output_name = tk.filedialog.asksaveasfile(
mode = 'wb',
defaultextension='pdf')
output.write(output_name)
Try to use tk.filedialog.asksaveasfilename instead of tk.filedialog.asksaveasfile. You just want the filename, not the file handler itself.
###Prompt the user for the file save###
output_name = tk.filedialog.asksaveasfilename(defaultextension='pdf')