我写了一个小型的调整大小工具,用于更改所有子文件夹中图片的大小。最后,我想删除原始文件。但是,该程序将删除las子文件夹中除最后一个文件以外的所有旧文件。 我是编程新手,是否缺少明显的东西?下面的代码:
# import relevant libraries
from tkinter import filedialog
import os
from PIL import Image
import time
# define stuff
width = 3872
height = 2592
# ask user to wait for start
print("Please wait a second")
# ask for directory
path = filedialog.askdirectory(initialdir=os.getcwd(), title="Please open image directory")
# iterate over images in directory and subdirectories:
for subdir, dirs, files in os.walk(path):
for file in files:
if file.endswith(".JPG"):
# open image
im = Image.open(os.path.join(subdir, file))
# resize with AA
im_res = im.resize((width, height), Image.ANTIALIAS)
# save image
im_res.save(os.path.join(subdir,"RESIZED - " + file))
# print name for progress
print(os.path.join(subdir, file + " - RESIZED"))
# close image
im.close()
im_res.close()
# remove old files
try:
for subdir, dirs, files in os.walk(path):
for file in files:
if file.startswith("DSC"):
os.remove(os.path.join(subdir, file))
except:
print()
print("RESIZING FINISHED - OLD FILES REMOVED - Window closes in 10s")
time.sleep(10)