user2355306
user2355306

Reputation: 387

Change the file extension for files in a folder?

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

Upvotes: 32

Views: 86352

Answers (8)

Maciej Skorski
Maciej Skorski

Reputation: 3354

Adding my few cents to improve @Keiku's answer: use Pathlib with its glob-backed search magic to simplify the code and enable fancy file matching.

For example, to rename all *.jpg into more proper *.jpeg (some APIs are strict about this distinction) in third-level directories, do:

from pathlib import Path

for path in Path("/home").glob("kaggle-data/*/*/*jpg"):
    path.rename(path.with_suffix('.jpeg'))

Upvotes: 1

Liam-Nothing
Liam-Nothing

Reputation: 167

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))

Upvotes: 0

Keiku
Keiku

Reputation: 8803

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

Upvotes: 2

chenaren
chenaren

Reputation: 2258

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.

Upvotes: 43

Jagdish
Jagdish

Reputation: 67

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

Upvotes: 2

Ricky Wilson
Ricky Wilson

Reputation: 3359

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

Upvotes: 0

elyase
elyase

Reputation: 40963

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

Upvotes: 20

kelsmj
kelsmj

Reputation: 1183

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

Upvotes: 12

Related Questions