how to open a folder of images (Python) - 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)

Related

app packed with pyinstaller don't open file from temporary directory (tkinter, tksvg, tempfile)

Hi everyone I have a problem with a simple app (at least the MRE is simple) packed with pyinstaller.
This desktop app should display a simple SVG file (I use tksvg).
My app first writes SVG into a temporary directory (writing is not as simple as in MRE), and then in the right moment displays it. It works nicely until I've packed it with pyinstaller.
My full app console throws me an error that the file can't be found. The path always ends with \tksvg. And such directory don't exist.
It looks as if tksvg would create such a subfolder but pyinstaller is missing such instructions?
Any ideas on what can I do?
Warning, total noob.
Thanks
from tkinter import *
import tempfile
import tksvg
root = Tk()
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
with open(temp_dir.name + f'\\test.svg', 'w') as a_file:
a_file.write('<svg viewBox="0 0 400 400"><rect x="0" y="0" width="400" height="400" fill="red" /></svg>')
svg_image = tksvg.SvgImage(file=temp_dir.name + f'\\test.svg')
show_svg = Label(root, image=svg_image)
show_svg.pack()
mainloop()
Edit
After some fight with the subject, I'm certain that it must be an issue with how pyinstaller packs libraries, a specially tksvg.
Method proposed by #JRiggles in itself works, but not with tksvg objects, and it's not necessary in my case (I use a temporary directory to manage files).
To check if the temporary directory works also when packed (pyinstaller), I've created "jpeg viewer" script and it works perfectly, even using PIL libraries.
from tkinter import *
import tempfile
from tkinter import filedialog
from PIL import Image, ImageTk
root = Tk()
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name) # just to check if temp. dir. was created
jpeg_file = filedialog.askopenfilename(filetypes=[("jpeg file", "*.jpeg")]) # opening file from disc
picture = Image.open(jpeg_file) # reading it with PIL library
picture.save(temp_dir.name+'\\test.jpeg') # saving image to temp. dir.
an_image = Image.open(temp_dir.name + '\\test.jpeg') # opening image from temp.dir.
the_image = ImageTk.PhotoImage(an_image) # reading image
show_image = Label(root, image=the_image) # setting label as "display"
show_image.pack() # showing the image
mainloop()
Does anyone has experience with SVG libraries, tksvg or any other, and how to make exe. with them?
Pyinstaller places your assets (images, icons, whatever) in a special directory that's created in your temp dir at runtime. I use this fetch_resource function to dynamically load assets when running a pyinstaller executable
import sys
from pathlib import Path
def fetch_resource(rsrc_path):
"""Loads resources from the temp dir used by pyinstaller executables"""
try:
base_path = Path(sys._MEIPASS)
except AttributeError:
return rsrc_path # not running as exe, just return the unaltered path
else:
return base_path.joinpath(rsrc_path)
In your case, you would use it like so:
svg_path = fetch_resource(r'path\to\test.svg')
with open(svg_path, 'w') as a_file:
...
svg_image = tksvg.SvgImage(file=svg_path)
You'll need to tell pyinstaller where to locate any files you want to 'fetch' by using the --add-data command-line or by adding the path to the datas list in your *.spec file
After some time it turn out that it was enough to add --collect-all="tksvg" to the pyinstaller. Maybe you could be more specific about what was missing in the compiled pack, but I have no competence to judge it, so I went for a safe collect-all.
THX

No such file or directory but all files in the same folder

I'm getting a
No such file or directory: 'SnP1000_TICKR.csv' error but all my files are in the following folder:
and I'm calling the file here
which is running on this piece of code:
def finVizEngine(input,output):
import chromedriver_autoinstaller
chromedriver_autoinstaller.install() # Check if the current version of chromedriver exists
# and if it doesn't exist, download it automatically,
# then add chromedriver to path
driver = webdriver.Chrome()
ipo_df = pd.DataFrame({})
openFinViz()
with open(input, 'r') as IPO_List:
csv_reader = reader(IPO_List)
This was running before, but then I uploaded files to Github and started running the files from vscode instead of pycharm and started to get a load of errors, but honestly don't understand what is wrong. Any help would be amazing,
Best Joao
First check in which folder it runs code
import os
print( os.getcwd() )
cwd means Current Working Directory.
If it runs in different folder then you have script then it also search csv in different folder.
The simplest method is to use "/full/path/to/SnP1000_TICKR.csv".
But more useful method is to get path to folder with script - like this
BASE = os.path.abspath(os.path.dirname(__file__))
and use it to create full path to file csv
input_full_path = os.path.join(BASE, "SnP1000_TICKR.csv")
output_full_path = os.path.join(BASE, "SnP1000_DATA.csv")
finVizEngine(input_full_path, output_full_path)
BTW:
If you will keep csv in subfolder data then you will need
input_full_path = os.path.join(BASE, "data", SnP1000_TICKR.csv")

OS Error:[WinError 123] The filename, directory name, or volume label syntax is incorrect

I am trying to save images after converting them into grayscale from one folder to another. when I run my code, it keeps saving the file in the same folder and making duplicates of all the images. Here is my code, Please guide where my problem lies...
import glob
import cv2
import os
spath=r"C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\*.png"
dpath=r"C:\Users\usama\Documents\FYP-Data\FYP Project Data\grayscale images\*.png"
files = os.listdir(spath)
for filename in glob.glob(r'C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\*.png'):
print(filename)
img=cv2.imread(filename)
rl=cv2.resize(img, (40,50))
gray_image = cv2.cvtColor(rl, cv2.COLOR_BGR2GRAY)
cv2.imwrite(os.path.join(dpath,filename), gray_image)
If you pass a full pathname to glob.glob(), then it will return the full path of the result files, not just the filenames.
That means in this loop in your code:
for filename in glob.glob(r'C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\*.png'):
filename is a full path such as C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\myfile1.png.
Then, later in the loop when you call cv2.imwrite(os.path.join(dpath,filename), gray_image), you're trying to join together C:\Users\usama\Documents\FYP-Data\FYP Project Data\grayscale images\*.png and C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\myfile1.png, which is the cause of your error.
glob() is convenient to get the full path of just the files you want, but then you have to separate the filename from the directory.
Try using listdir() instead of glob():
import glob
import cv2
import os
sdir=r"C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza"
ddir=r"C:\Users\usama\Documents\FYP-Data\FYP Project Data\grayscale images"
for filename in os.listdir(sdir):
if not filename.lower().endswith(".png"):
continue
print(filename)
img=cv2.imread(os.path.join(sdir, filename))
rl=cv2.resize(img, (40,50))
gray_image = cv2.cvtColor(rl, cv2.COLOR_BGR2GRAY)
cv2.imwrite(os.path.join(ddir,filename), gray_image)

How to copy alternate images from one folder to another in python

I want to implement a python code which would select a 1 image after 3 images and so on till the last image in an sequential manner in the specified folder and copy those images to another folder.
Example : As shown in the screenshot
link : https://i.stack.imgur.com/DPdOd.png
The solution is same but I think it is more clear for all
import os
import shutil
path_to_your_files = 'your pics path'
copy_to_path = 'destination for your copy'
files_list = sorted(os.listdir(path_to_your_files))
orders = range(1, len(files_list) , 4)
for order in orders:
files = files_list[order] # getting 1 image after 3 images
shutil.copyfile(os.path.join(path_to_your_files, files), os.path.join(copy_to_path, files)) # copying images to destination folder
You can:
import os
files = os.listdir('YOUR PICS DIRECTORY HERE')
every_4th_files=[f for idx,f in zip(range(len(files)), files) if not idx%4]
Is it what you need?
Edit
To copy images I recommend to use shutil.copyfile.
If you encounter a problem - inform about it.
import os
from shutil import copyfile
files = sorted(os.listdir('Source Folder'))
4thFile = [fileName for index, file in zip(range(len(files)),files) if not index%4]
for file in 4thFile:
copyfile(os.path.join(src_path, f), os.path.join(dest_path, file))
That should get the job done.

PermissionError when copying files using shutil.copyfile

I am a beginner in python and this is my first application.
So, basically, the application takes a folder with mp3 files in it, and reads the metadata for artist name, and then sorts the songs accordingly by copying them into newly created sub-folders named after the artist name. If there's no artist name, it would create a folder called 'unsorted' and copy files into that. I have got to the point of being able to create new folders, but the last bit which is copying the files gives me a PermissionError. Below are the code and the error I am getting.
import os
import eyed3
import shutil
# get the path to music directory
musicFolder = input('please enter the full path of your music folder : ')
correctedPath = musicFolder.replace('/', '//')
musicList = []
# list of audio file objects
for _files in os.listdir(correctedPath):
if _files.endswith('.mp3'):
musicList.append(eyed3.load(correctedPath + '//' + _files))
sortedFolder = ''
# check tag info for album artist, and sort to folders
for _audioFiles in musicList:
if _audioFiles.tag.album_artist != None:
sortedFolder = correctedPath + '//' + _audioFiles.tag.album_artist
else:
sortedFolder = correctedPath + '//' + 'Unsorted'
if not os.path.exists(sortedFolder):
os.mkdir(sortedFolder)
shutil.copyfile(_audioFiles.path, sortedFolder)
Error
PermissionError: [Errno 13] Permission denied: 'C://Users//Manu//Music//Music Test//Coldplay'
Any help is highly appreciated.
Thanks for your time.
It looks to me like you are using forward slash / where you should be using backslash .
'C://Users//Manu//Music//Music Test//Coldplay'
should be
'C:\\Users\\Manu\\Music\\Music Test\\Coldplay'
Better yet, Python has built in libraries to assist with paths: os.path and pathlib.
https://medium.com/#ageitgey/python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f
shutil.copy2(src,dst) fixed it for me. I changed it from shutil.copyfile.
shutil copy functions

Categories