30

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')
martineau
  • 119,623
  • 25
  • 170
  • 301
user2355306
  • 367
  • 1
  • 6
  • 14

7 Answers7

41

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.

jTiKey
  • 696
  • 5
  • 13
chenaren
  • 2,090
  • 1
  • 19
  • 24
  • Thank you, as you recommended I changed the position of the line ,it proceed but again would sotck on the line 'outfile = open(output,'w')' – user2355306 May 24 '13 at 13:45
  • @user2355306 `os.rename` doesn't seem to return the file path. – chenaren May 24 '13 at 13:48
  • replace is not correct, for example file can have name Smth.grform.grf, @elyase answer is better – Alexander Danilov Jan 21 '16 at 18:50
  • What is the usage of this line `oldbase = os.path.splitext(filename)` ? – S.Sakthybaalan Nov 11 '19 at 08:55
  • @chenaren @jTiKey thank you very much for the codes. however, my files have no any extensions for example, and i would like to put an extension to each file in a folder. in this case, i will be very happy if you have any suggestions... i am not sure this will be still available for my case: `newname = infilename.replace('.grf', '.las')` – vdu16 Nov 23 '21 at 11:36
  • @vdu16 just do `newname = infilename + '.jpg' ` where .jpg is your extension – jTiKey Nov 24 '21 at 08:12
19

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')
elyase
  • 39,479
  • 12
  • 112
  • 119
  • it's wrong. it adds two dots instead of one in the extestion of the file last line must be changed into: os.rename(filename, filename[:-4] + '.las') – DaniPaniz Jun 26 '16 at 15:29
  • @DaniPaniz, sorry what is the difference between your suggestion and what i wrote in my answer? – elyase Jun 27 '16 at 00:46
  • I guess it was "-3" in an older version, someone changed it to the correct one – DaniPaniz Jul 03 '16 at 16:33
  • Great.@elyase how to extend this to subdirectories which also has files to be renamed ? – AAI Sep 01 '17 at 16:34
12

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")
kelsmj
  • 1,183
  • 11
  • 18
  • Thank you for your guidance. using this code, the running process wouls stock on the last line with the error' system can not find the data' what would be the reason? – user2355306 May 24 '13 at 13:54
2

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')
Jagdish
  • 67
  • 6
  • Thank you for your answer. Please explain what the code you're providing does and what it adds in comparison with the previously existing answers. Also, please avoid using [`dir`](https://docs.python.org/3/library/functions.html#dir) as a variable name. I would also suggest considering unpacking as follows: `root, ext = os.path.splitext(files)`. – PiCTo Dec 03 '19 at 18:41
0
#!/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()
Ricky Wilson
  • 3,187
  • 4
  • 24
  • 29
0

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'))
Keiku
  • 8,205
  • 4
  • 41
  • 44
0

With print and validation.

import os
from os import walk

mypath = r"C:\Users\you\Desktop\test"
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))
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Liam-Nothing
  • 167
  • 8