Skip to main content

Change an extension to file in python

Program to change an extension of a file in python:

import os

import shutil


def renamefiles():

    filelist = os.listdir(r"source path here")

    print(filelist)

    os.chdir(r"source path here")

    path = os.getcwd()

    for filename in filelist:

        if filename.endswith(".xml"):

            print("Old Name - " + filename)

            (prefix, sep, sffix) = filename.rpartition(".")

            newfile = filename + '.ok'

            if not filename.endswith(".ok"):

                os.rename(filename, newfile)

                print("New Name - " + newfile)

                os.chdir(path)



# path to source directory

src_dir = r'source path here'


# path to destination directory

dest_dir = r'File Backup path here'


# getting all the files in the source directory

files = os.listdir(src_dir)

shutil.copytree(src_dir, dest_dir)


renamefiles()


Comments