chinna
chinna

Reputation: 55

How to change the files extension using python

In a Folder, I have 100 files with extensions '.txt','.doc','.pdf'. I need to rename the files as:

  1. If the filename ends with '.txt' -> replace filename ends with '.jpg'
  2. If the filename ends with '.doc' -> replace filename ends with '.mp3'
  3. If the filename ends with '.pdf' -> replace filename ends with '.mp4'

I have tried this one so far

import os,sys

folder ="C:/Users/TestFolder"
for filename in os.listdir(folder):
    base_file, ext = os.path.splitext(filename)
    print(ext)
    if ext == '.txt':
        print("------")
        print(filename)
        print(base_file)
        print(ext)
        os.rename(filename, base_file + '.jpg')

    elif ext == '.doc':
        print("------")
        os.rename(filename, base_file + '.mp3')

    elif ext == '.pdf':
        print("------")
        os.rename(filename, base_file + '.mp4')
    else:
        print("Not found")

Upvotes: 0

Views: 5391

Answers (1)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

To begin with , you can store your mappings in a dictionary, then when you are iterating over your folder, and you find the extension, just use the mapping to make the new file name and save it.

import os

folder ="C:/Users/TestFolder"

#Dictionary for extension mappings 
rename_dict = {'txt': 'jpg', 'doc': 'mp3', 'pdf': 'mp4'}
for filename in os.listdir(folder):

    #Get the extension and remove . from it
    base_file, ext = os.path.splitext(filename)
    ext = ext.replace('.','')

    #If you find the extension to rename
    if ext in rename_dict:
        #Create the new file name
        new_ext = rename_dict[ext]
        new_file = base_file + '.' + new_ext

        #Create the full old and new path
        old_path = os.path.join(folder, filename)
        new_path = os.path.join(folder, new_file)

        #Rename the file
        os.rename(old_path, new_path)

Upvotes: 1

Related Questions