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