Home > Back-end >  How to loop over a folder, and recreate them in another folder with same structure?
How to loop over a folder, and recreate them in another folder with same structure?

Time:01-27

I want to process a folder and blur the images and recreate them in another folder while preserving the structure.

My source folder has the following structure

Data/
   test1/
      test2/
         6.png
      4.png
      5.jpeg
   1.jpg/
   2.jpg
   3.jpeg

I wanted to blur all these images and save them in another folder

src = 'C:\Users\shakhansho\Downloads\Data' #folder with images
dst = 'C:\Users\shakhansho\Downloads\Output' #folder for output

let's say I have a function which takes a path to image and then applies blurring and then saves it in the same directory blur(path_to_img)

How can I loop over the src files, blur and then save in dst folder with preserving the structure.I would like the dst folder contain the same folder name and image names but blurred.

CodePudding user response:

I would advise using glob.glob (or glob.iglob) for this. It can recursively find all files under a directory. Then, we can simply open the images in some way, transform them, find the output file and folder, optionally create that folder, and write out transformed images. The code contains comments to elaborate these steps slightly.

import glob
import os

# Recursively find all files under Data/
for filepath in glob.iglob("Data/**/*.*", recursive=True):
    # Ignore non images
    if not filepath.endswith((".png", ".jpg", ".jpeg")):
        continue

    # Open your image and perform your transformation
    # to get the blurred image
    with open(filepath, "r") as f:
        image = f.read()
        blurred = transform(image)
    
    # Get the output file and folder path
    output_filepath = filepath.replace("Data", "Output")
    output_dir = os.path.dirname(output_filepath)
    # Ensure the folder exists
    os.makedirs(output_dir, exist_ok=True)

    # Write your blurred output files
    with open(output_filepath, "w") as f:
        f.write(blurred)

I recreated your file structure, and my program was able to re-create the exact file structure, but under Output instead.

  •  Tags:  
  • Related