I have this code, it origionally comes from here: renaming files base on the file structure
I added a thumbnail save as to the function from here: Create thumbnail images for jpegs with python
I'm trying to select all files from a directory structure, rename them based on the file structure. I've added a filter using 'in', but I can't get the resize as thumbnail bit to work.
Name Image is not defined.
import os
import shutil
#testing
import sys
import image
def image_thumb_filter():
size = 128, 128
for path, dirs, files in os.walk(wd):
for file in files:
if file.endswith(".jpg"):
src = os.path.join(path, file)
#print(src)
dst = os.path.join(os.getcwd(), "Photo_selection")
if not os.path.exists(dst): #Checks 'Photos_mirror' folder exists
otherwise creates
os.makedirs(dst)
new_name = src.replace(wd+'\\', '').replace('\\', '_')
new_dst = os.path.join(dst, new_name + "_thumb")
if not os.path.isfile(new_dst):
if "99\\526" in src:
try:
im = image.open(src)
im.thumbnail(size)
im.save(new_dst, "JPEG")
except IOError:
print ("cannot create thumbnail for", infile)
shutil.copy(src, dst)
old_dst = os.path.join(dst, file)
#Assuming your /dir/dir/... structure is inside of your working
directory (wd)
os.rename(old_dst, new_dst)
else: # it doesn't like this else statement
continue
image_thumb_filter()
You have not defined the object "Image" specifically anywhere in your code. Remember that Python and many other languages are case sensitive. Maybe you meant "image?"
Related
I'm attempting to write a script that will save a file in the given directory, but I'm getting a NotADirecotryError[WinError 267] whenever I run it. Any ideas or tips on what I may have done incorrectly?
import shutil
import os
src = 'C:\\Users\\SpecificUsername\\Pictures\\test.txt\'
dest = 'C:\\Users\\SpecificUsername\\Desktop'
files = os.listdir(src)
for file in files:
shutil.copy(file, dest)
for file in files:
if os.path.isfile(file):
shutil.copy(file,dest) ```
There are a couple of things going on here:
You can just use forward slashes in the paths.
Your src is the test.txt file, and not a directory, so you cannot iterate over it using os.listdir().
You can also merge the two loops together since they are looping over the same set of data.
shutil.copy() takes a file path as input, while what you are passing is a filename.
The following code should work and it also copies directories as is:
import shutil
import os
basepath = "C:/Users/SpecificUsername/"
src = "Pictures/"
dest = "Desktop/"
files = os.listdir(os.path.join(basepath, src))
for filename in files:
filepath = os.path.join(basepath, src, filename)
if (os.path.isfile(filepath)):
print("File: " + filename)
shutil.copy(filepath,dest)
else:
print("Dir: " + filename)
shutil.copytree(filepath, os.path.join(dest, filename))
Hope it helps!
I'm trying to convert all files from a directory from .jpg to .png. The name should remain the same, just the format would change.
I've been doing some researches and came to this:
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
im.save('img11.png')
print(os.path.join(directory, filename))
continue
else:
continue
I was expecting the loop to go through all my .jpg files and convert them to .png files. So far I was doing only with 1 name: 'img11.png', I haven't succed to build something able to write the adequate names.
The print(os.path.join(directory, filename)) works, it prints all my files but concerning the converting part, it only works for 1 file.
Do you guys have any idea for helping me going through the process?
You can convert the opened image as RGB and then you can save it in any format.
You can try the following code :
from PIL import Image
import os
directory = r'D:\PATH'
c=1
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
name='img'+str(c)+'.png'
rgb_im = im.convert('RGB')
rgb_im.save(name)
c+=1
print(os.path.join(directory, filename))
continue
else:
continue
You're explicitly saving every file as img11.png.
You should get the name of your jpg file and then use that to name and save the png file.
name = filename[:-4]
im.save(name + '.png')
I would have used os.rename() function like below.
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
prefix = filename.split(".jpg")[0]
os.rename(filename, prefix+".png")
Please let me know if this is what you wanted. Try the code with some copied images inside a test folder, before applying to the intended folder. All the best.
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
prefix = filename.split(".jpg")[0]
im = Image.open(filename)
im.save(prefix+'.png')
else:
continue
Please try this one and let me know.
I am trying to create a script that moves all pictures from my downloads folder, to my pictures folder. My script works this far (moving the files over), except when it tries to move a file that already has the same name in the destination folder - like with printscreens. It will not move the file if printscreen1.png already exists in pictures.
For files like this, I would like to rename the file and add the date or time to the file name, then move it without replacing the original printscreen so I can keep both and all printscreens going toward the future.
import os
import shutil
import datetime
downloadsb = os.path.join('B:\\Downloads')
pictures = os.path.join('B:\\Pictures')
for f in os.listdir(downloadsb):
if f.endswith((".jpg", ".gif", ".jpeg", ".png", ".ico", ".psd", ".sfw", ".webp", ".pdd", ".psb", ".bmp", ".rle", ".dib", ".eps", ".iff", ".tdi", ".jpf",
".jpx", ".jp2", ".j2c", ".jxk", ".jpc", ".jps", ".mp0", ".pcx", ".pdp", ".raw", ".pxr", ".pns")):
shutil.move(os.path.join(downloadsb, f), pictures)
if os.path.isfile(f):
os.rename(f,f + "date")
Here is my error message:
raise Error, "Destination path '%s' already exists" % real_dst
shutil.Error: Destination path 'B:\Pictures\printscreen1.png' already exists
This is what I have so far, I would appreciate any help or advice. Thank you
There's a built-in library that checks to see if a file is an image. Also, you need to iterate over the files in the directory (folder). Something like this should work (not tested):
import os
import shutil
import datetime
import imghdr
downloadsb = os.path.join('B:\\Downloads')
pictures = os.path.join('B:\\Pictures')
files = os.listdir(downloadsb)
for f in files:
try:
imghdr.what(f)
dest_name = f
if os.path.exists( os.path.join(pictures, dest_name) ):
dest_name += datetime.datetime.now().strftime('%H%M%S')
shutil.move(os.path.join(downloadsb, f),
os.path.join(pictures, dest_name))
except Exception as e:
continue
Why not check it before moving. Something like below
NOTE: When the file exists you can do different types of renaming. I and just appending _new (to the extension). Not quite what you wanted but that should give an idea
import os
import shutil
import datetime
import glob
downloadsb = os.path.join('src')
pictures = os.path.join('dst')
for f in glob.glob(downloadsb + '/*'):
if f.endswith(
(".jpg", ".gif", ".jpeg", ".png", ".ico", ".psd", ".sfw", ".webp", ".pdd", ".psb", ".bmp",
".rle", ".dib", ".eps", ".iff", ".tdi", ".jpf", ".jpx", ".jp2", ".j2c", ".jxk", ".jpc", ".jps",
".mp0", ".pcx", ".pdp", ".raw", ".pxr", ".pns")):
dstFile = os.path.join(pictures, os.path.split(f)[1])
if os.path.exists(dstFile):
# Do whatever you want to rename the file here
shutil.move(f, dstFile + '_new')
else:
shutil.move(f, dstFile)
Before running
dst:
tmp.jpg
src:
tmp.jpg
After running
dst:
tmp.jpg tmp.jpg_new
src:
I have code with looks through a folder 'Images' and then subfolders and processes all those images.
I now need to save those images to a parallel directory, i.e. a folder called 'Processed Images' (in same directory as 'Images' folder) and then to the subfolders within this folder - these subfolders are named the same as the subfolders in 'Images' - the image should save to the same name of subfolder that it came from.
I can get the images to save to 'Processed Images' but not the subfolders within it.
path = ("...\\Images")
for dirName, subdirList, fileList, in os.walk(path):
for file in fileList:
full_file_path = os.path.join(dirName, file)
if file.endswith((".jpg")):
image_file = Image.open(full_file_path)
image_file = image_file.convert('L')
image_file = PIL.ImageOps.invert(image_file)
image_file = image_file.resize((28, 28))
new_filename = file.split('.jpg')[0] + 'new.png'
path2 = ("...\\Processed Images")
image_file.save(os.path.join(path2, new_filename))
else: continue
You can use the function os.mkdir() to create a new folder. dirName returned by os.walk() gives you the current folder path, so you can just extract the part of the path that you need, append it to ...\\Processed Images and create the new folder if needed.
Be sure to use two separate folder trees for the input files and output files. Otherwise os.walk() will find the new directories with the output images and continue to iterate over them.
I think you can seriously simplify this code using pathlib. I’m not sure about the triple dots (I think they should be double) in your base paths but they may work for you.
from pathlib import Path
path = Path("...\\Images")
path2 = Path("...\\Processed Images")
path2.mkdir(exist_ok=True)
for jpg_file in p.glob('**/*.jpg'):
full_file_path = str(jpg_file)
image_file = Image.open(full_file_path)
image_file = image_file.convert('L')
image_file = PIL.ImageOps.invert(image_file)
image_file = image_file.resize((28, 28))
new_filename = jpg_file.stem + 'new.png'
image_file.save(str(path2 / new_filename))
I tried to make a program which delete all of the empty files ( whose size is zero ). Then, i run the program by dragging the script file in "command prompt" and run it .
However, no empty files had deleted (but i have some of them).
Please help me to find the error in my code.
import os
a = os.listdir('C:\\Python27')
for folder in a :
sizes = os.stat('C:\\Python27')
b = sizes.st_size
s = folder
if b == 0 :
remove('C:\\Python27\s')
You're assigning the values iterator os.listdir returns to folder and yet you aren't using it at all in os.stat or os.remove, but instead you are passing to them fixed values that you don't need.
You should do something like this:
import os
dir = 'C:\\Python27'
for file_name in os.listdir(dir):
file_path = os.path.join(dir, file_name)
if os.stat(file_path).st_size == 0:
os.remove(file_path)
You can delete something like the following code and you need to add some exception handling. I have used a test folder name to demonstrate.
import os
import sys
dir = 'c:/temp/testfolder'
for root, dirs, files in os.walk(dir):
for file in files:
fname = os.path.join(root, file)
try:
if os.path.getsize(fname) == 0:
print("Removing file %s" %(fname))
os.remove(fname)
except:
print("error: unable to remove 0 byte file")
raise