Change the file extension for files in a folder?

Question:

I would like to change the extension of the files in specific folder. i read about this topic in the forum. using does ideas, I have written following code and I expect that it would work but it does not. I would be thankful for any guidance to find my mistake.

   import os,sys
   folder = 'E:/.../1936342-G/test'
   for filename in os.listdir(folder):
           infilename = os.path.join(folder,filename)
           if not os.path.isfile(infilename): continue
           oldbase = os.path.splitext(filename)
           infile= open(infilename, 'r')
           newname = infilename.replace('.grf', '.las')
           output = os.rename(infilename, newname)
           outfile = open(output,'w')
Asked By: user2355306

||

Answers:

Something like this will rename all files in the executing directory that end in .txt to .text

import os, sys

for filename in os.listdir(os.path.dirname(os.path.abspath(__file__))):
  base_file, ext = os.path.splitext(filename)
  if ext == ".txt":
    os.rename(filename, base_file + ".text")
Answered By: kelsmj

The open on the source file is unnecessary, since os.rename only needs the source and destination paths to get the job done. Moreover, os.rename always returns None, so it doesn’t make sense to call open on its return value.

import os
import sys
folder = 'E:/.../1936342-G/test'
for filename in os.listdir(folder):
    infilename = os.path.join(folder,filename)
    if not os.path.isfile(infilename): continue
    oldbase = os.path.splitext(filename)
    newname = infilename.replace('.grf', '.las')
    output = os.rename(infilename, newname)

I simply removed the two open. Check if this works for you.

Answered By: chenaren

You don’t need to open the files to rename them, os.rename only needs their paths. Also consider using the glob module:

import glob, os

for filename in glob.iglob(os.path.join(folder, '*.grf')):
    os.rename(filename, filename[:-4] + '.las')
Answered By: elyase
#!/usr/bin/env python

'''
Batch renames file's extension in a given directory
'''

import os
import sys
from os.path import join
from os.path import splitext

def main():
    try:
        work_dir, old_ext, new_ext = sys.argv[1:]
    except ValueError:
        sys.exit("Usage: {} directory old-ext new-ext".format(__file__))

    for filename in os.listdir(work_dir):
        if old_ext == splitext(filename)[1]:
            newfile = filename.replace(old_ext, new_ext)
            os.rename(join(work_dir, filename), join(work_dir, newfile))


if __name__ == '__main__':
    main()
Answered By: Ricky Wilson

import os

dir =("C:\Users\jmathpal\Desktop\Jupyter\Arista")
for i in os.listdir(dir):
    files = os.path.join(dir,i)
    split= os.path.splitext(files)
    if split[1]=='.txt':
       os.rename(files,split[0]+'.csv')
Answered By: Jagdish

If you have python 3.4 or later, you can use pathlib. It is as follows. This example is for changing .txt to .md.

from pathlib import Path

path = Path('./dir')

for f in path.iterdir():
    if f.is_file() and f.suffix in ['.txt']:
        f.rename(f.with_suffix('.md'))
Answered By: Keiku

With print and validation.

import os
from os import walk

mypath = r"C:UsersyouDesktoptest"
suffix = ".png"
replace_suffix = ".jpg"
filenames = next(walk(mypath), (None, None, []))[2]
for filename in filenames:
    if suffix in filename:
        print(filename)
rep =  input('Press y to valid rename : ')
if rep == "y":
    for filename in filenames:
        if suffix in filename:
            os.rename(mypath+"\"+filename, mypath+"\"+filename.replace(suffix, replace_suffix))
Answered By: Liam-Nothing
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.