Get files from a folder and rename in Python

I had encountered a specific scenario and am going to discuss the scenario and its solution. I had over 400 images in a folder on my laptop and wanted to compress these images.

I had used an online portal to compress these images. The online portal had added "-min" as suffix to each of the images after compression.

My requirement was to get the list of images and rename these images after removing "-min".

I have used Python for the above requirement and here are the steps.

# get list of all files
import os
from os import path
for root, dirs, files in os.walk("C:\\Users\\Me\\level3\\"):
    for file in files:
        if file.endswith(".png"):
            # remove -min string from the name
            changed_name = file.replace('-min',"")
            # rename a file
            os.rename(os.path.join(root, file),os.path.join(root, changed_name))

For the related to scenario, wanted to use online portal to compress a image and get the compressed stored into a folder. The online portal had API available to allow me to write Python code to compress images.

I have imported the package

import tinify
# Register and get the API Key
tinify.key = "#####"

Now get iteratively upload a file and get the compressed file stored into a folder.

import os
from os import path
source_path="C:\\Users\\ramg_\\source\\"
destination_path="C:\\Users\\ramg_\\compressed images\\"

for root, dirs, files in os.walk(source_path):
    for file in files:
        source = tinify.from_file(os.path.join(source_path,file))
        source.to_file(os.path.join(destination_path,file))

Leave a Comment