Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the file extension for files in a folder?

Tags:

python

file

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')
like image 368
user2355306 Avatar asked May 24 '13 13:05

user2355306


People also ask

Can you convert files by changing extension?

You can also do it by right-clicking on the unopened file and clicking on the “Rename” option. Simply change the extension to whatever file format you want and your computer will do the conversion work for you.


3 Answers

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.

like image 199
chenaren Avatar answered Oct 19 '22 00:10

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')
like image 19
elyase Avatar answered Oct 19 '22 02:10

elyase


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")
like image 12
kelsmj Avatar answered Oct 19 '22 02:10

kelsmj