26
votes

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')
5
In what manner does it not work? Do the files just not get renamed? Is the any error messages? - dbr
Thank you for your reply. Well, it stops in the line ' output = os.rename(infilename, newname)' - user2355306
It just stops? Without any output? - glglgl

5 Answers

36
votes

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.

19
votes

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')
11
votes

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")
2
votes

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')
0
votes
#!/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()