By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,592 Members | 1,569 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,592 IT Pros & Developers. It's quick & easy.

change extensions

P: n/a
how can i change all files from one extension to another within a direcory?
Jul 18 '05 #1
Share this Question
Share on Google+
5 Replies


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


Using os.listdir, os.path.split and os.rename.

-- Gerhard
Jul 18 '05 #2

P: n/a
Bob Then wrote:
how can i change all files from one extension to another within a

direcory?

This should work:

import os

def change_exts(suffix, new_suffix, dir_name):
for name in os.listdir(dir_name):
if name.endswith(suffix):
old_pathname = os.path.join(dir_name, name)
new_pathname = old_pathname[:-len(suffix)] + new_suffix
os.rename(old_pathname, new_pathname)

David.

Jul 18 '05 #3

P: n/a
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
Jul 18 '05 #4

P: n/a
On Apr 5, 2005 10:43 AM, Jeffrey Maitland <ma***@vianet.ca> wrote:
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'))


you should really use in_file.splitext - your script renames
myfile.with.lots.of.dots.txt to myfile.text instead of
myfile.with.lots.of.dots.text .

If you *really* wanted to use split(), it oughta be
''.join(in_file.split('.')[:-1]) , but why not use the built-in?

Peace
Bill Mill
bill.mill at gmail.com
Jul 18 '05 #5

P: n/a
Tim Roberts wrote:
"Bob Then" <bo******@yahoo.com.au> wrote:
how can i change all files from one extension to another within a direcory?


In Windows, the quickest way is:

os.system( "rename *.old *.new" )


I have a vague memory that this won't work on
all versions of Windows... possibly it isn't
supported on Win98? That may not be quite right,
but I recall problems doing this in the past.
(Or was it just DOS that failed?)

-Peter
Jul 18 '05 #6

This discussion thread is closed

Replies have been disabled for this discussion.