looping over images in a directory - linux

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).

Related

PyPDF2 append_function can't find file

I want to use the PyPDF2 module to merge PDFs.
The following code works fine:
import PyPDF2
import sys
import os
input_path = r'\Users\XXXXX\OneDrive\Desktop\PDF_File_Input'
merger = PyPDF2.PdfFileMerger()
for file in os.listdir(input_path):
if file.endswith(".pdf"):
print(file)
As soon as I implement the append function I'm getting a traceback error from line 10. FileNotFoundError: [Errno 2] No such file or directory: 'abc.pdf'
import PyPDF2
import sys
import os
input_path = r'\Users\XXXXX\OneDrive\Desktop\PDF_File_Input'
merger = PyPDF2.PdfFileMerger()
for file in os.listdir(input_path):
if file.endswith(".pdf"):
merger.append(file)
merger.write("combined_file.pdf")
I don't understand why the file can be found via print but not by the append function.
If the path is correct, then most likely has something to do with the way you implement the Merger.
def run_mergepdf(args):
check_required(args, ["input", "output"])
print("Number of input files: {0}".format(len(args.input)))
#Preliminary checks
print("Checking read/write status")
check_files(args.input, action="r")
check_files([args.output], action="w")
#Join pdfs
print("Starting to merge PDFs")
merger = PdfFileMerger(strict=False)
for pdf in args.input:
if os.stat(pdf).st_size != 0:
merger.append(PdfFileReader(pdf))
print("Writing merged file: {0}".format(args.output))
merger.write(args.output)
print("PDFs merged successfully!")

Error when reading INI file using configparser

Here is my ini file parameters.ini:
[parameters]
Vendor = Cat
Here is my python code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import codecs
import sys
import os
import configparser
### Script with INI file:
INI_fileName="parameters.ini"
if not os.path.exists(INI_fileName):
print("file does not exist")
quit()
print("Here is the INI_fileName: " + INI_fileName)
config = configparser.ConfigParser()
config.read('INI_fileName')
vendor = config['parameters']['Vendor']
print("Here is the vendor name: " + vendor)
Here is the error:
python3 configParser-test.py
Here is the INI_fileName: parameters.ini
Traceback (most recent call last):
File "configParser-test.py", line 18, in <module>
vendor = config['parameters']['Vendor']
File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/configparser.py", line 958, in __getitem__
raise KeyError(key)
KeyError: 'parameters'
If I run the same code interactively it works. However if it was related to the file path, the error would be different, I assume: "file does not exist". Interactively:
>>> print(INI_fileName)
parameters.ini
>>> config.read('INI_fileName')
[]
>>> config.read('parameters.ini')
['parameters.ini']
>>>
Why is it not picking up the file name?
While playing with the interactive command I think I found the reason. Since I use the filename as variable i do not need to use quotes! Omg...
config.read(INI_fileName)
This problem may be due to the UTF byte order mark (BOM) added by Windows text editor.
BOM should be deleted before reading the config parameters in Linux/Unix.
Try:
config = configparser.ConfigParser()
config_file_path = '/app/config.ini' # full absolute path here!
s = open(config_file_path, mode='r', encoding='utf-8-sig').read()
open(config_file_path, mode='w', encoding='utf-8').write(s)
config.read(config_file_path)
# now check if it is OK

Python: copy file tree to a text file

I'm trying to create a text file with a tree of all files / dirs from a place that I choose using os.chdir(). My approach is to print the tree and to save all prints to the text file. The problem is that it doesn't copy the printed tree and the file is blank.
What am I doing wrong?
And is there a way to write this kind of data to the file without to actually print it?
My code:
import os
import sys
f = open("tree.txt", "w")
os.chdir("c:\\Users\Daniel\Desktop")
sys.stdout = f
os.system("tree /f")
f.close()
Edit
I was able to get the file tree from the clipboard after executing the command, however it gives me and eror when it tried to write to the txt file.
code:
import os
import tkinter
with open("tree.txt", "w") as f:
os.system("tree /f |clip")
root = tkinter.Tk()
tree = root.clipboard_get()
print(tree)
f.write(tree)
eror:
Traceback (most recent call last):
File "c:\Users\Daniel\Desktop\Tick\code_test\files.py", line 9, in <module>
f.write(tree)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38-32\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2502' in position 80: character maps to <undefined>
solution
So I found the problem, I needed to use codec to be able write unicode to the text file. Now it works very well
code:
import os
import tkinter
import codecs
with codecs.open("tree.txt", "w", "utf8") as f:
os.chdir("c:\\Users")
os.system("tree /f |clip")
root = tkinter.Tk()
tree = root.clipboard_get()
f.write(tree)
Method check_output from subprocess module can help you to catch program output:
import subprocess
f = open("tree.txt", "wb")
tree_output = subprocess.check_output('tree /f', shell=True, cwd=r'c:\Users\Daniel\Desktop')
f.write(tree_output)
f.close()
Or with context manager:
import subprocess
with open("tree.txt", "wb") as f:
f.write(subprocess.check_output('tree /f', shell=True, cwd=r'c:\Users\Daniel\Desktop'))
Option wb is required because check_output returns bytes not a str. If you want to process output like a string - call tree_output.decode() first.

Error when loading audio file from zip in python

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))

python 3 import not working

I am new to Python 3 and am rewriting a Python 2 program. I have the following file system:
|-00_programs / test.py
|-01_classes / class_scrapper.py
I want to import the class scrapper from the file class_scrapper:
Here is class_scrapper.py:
# -*- coding: utf-8 -*-
from urllib.request import urlopen
from bs4 import BeautifulSoup
class scrapper:
def get_html(self, url):
html = False
headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' }
try:
html = urlopen(url, '', headers).read()
except Exception as e:
print ("Error getting html :" + str(e))
return html
Here is test.py:
# -*- coding: utf-8 -*-
import sys
sys.path.insert(0, "./../01_classes/class_scrapper.py")
from class_scrapper import scrapper
o_scrapper = scrapper()
While executing I got:
Traceback (most recent call last):
File "/src/00_programs/tets.py", line 6, in <module>
from class_scrapper import scrapper
ImportError: No module named 'class_scrapper'
What should be changed on the import command to make that work?
Thanks,
Romain.
If the interpreter is saying module doesn't exist, it means you must have spelt it wrong when importing, or the module is either not in your program's directory or the python directory which has all of the other main modules.

Resources