Convert tif to png

I’m trying to use a For loop to go through a list of ‘tif’ files to rename to PNG. I am not sure how to implement the For lop. Could anyone help please? Many Thanks

import re           # add this to your other imports

#src = path.realpath("Position014 (RGB rendering) - 1024 x 1024 x 1 x 1 - 3 ch (8 bits).tif")
for dir, subdirs, files in os.walk("."):
	for f in files:

folder = src.split(os.sep)[-2]

name_elements = re.findall(r'(Position)(\d+)', src)[0]
name = name_elements[0] + str(int(name_elements[1]))
print(name)       # just for demonstration

dst = folder + '_' + name + ".png"

os.rename('Position014 (RGB rendering) - 1024 x 1024 x 1 x 1 - 3 ch (8 bits).tif', dst)

Hi Alameer Ali,

Just changing the file extension from “tif” to “png” isn’t going to
change the file from a TIF file to a PNG file. Unless the files are
actually PNG files that have been misnamed with tif somehow, all you
will do is confuse people and possibly prevent the files from being
opened or edited.

(Some image processing software is smart enough to ignore the file
extension but others will be very confused by the wrong file extension.)

Does something like this help?

# Untested.
import os
for dir, subdirs, files in os.walk("."):
    for filename in files:
        base, ext = os.path.splitext(filename)
        if ext.lower() == '.tif':
            src = os.path.join(dir, filename)
            dest = os.path.join(dir, base + '.png')
            if not os.path.exists(dest):
                os.rename(src, dest)