change extensions

Jeffrey Maitland maitj at vianet.ca
Tue Apr 5 10:43:35 EDT 2005


That approach works, but so does this one. 

import os, glob

input_file_list = glob.glob('*.txt')
for in_file in input_file_list:
    name = in_file.split('.')
    os.rename(in_file, str(name[0]) + '.' + 'text')) 

# I could have put the text extension with the period but if you use a
variable (string) for the extension then you can't

-----Original Message-----
From: python-list-bounces+maitj=vianet.ca at python.org
[mailto:python-list-bounces+maitj=vianet.ca at python.org] On Behalf Of
Peter Hansen
Sent: Tuesday, April 05, 2005 10:35 AM
To: python-list at python.org
Subject: Re: change extensions

Bob Then wrote:
> how can i change all files from one extension to another within a
direcory?

Using Jason Orendorff's path.py module:

# change all .py files in '.' to extension .new
from path import path

for f in path('.').files():
     if f.endswith('.py'):
         f.rename(f.splitext()[0] + '.new')



Don't try the above in a folder containing useful
Python files! ;-)

-Peter
-- 
http://mail.python.org/mailman/listinfo/python-list






More information about the Python-list mailing list