change extensions

?

=?ISO-8859-1?Q?Gerhard_H=E4ring?=

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

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

-- Gerhard
 
D

David Wilson

Bob said:
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.
 
P

Peter Hansen

Bob said:
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
 
B

Bill Mill

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
 
T

Tim Roberts

Bob Then said:
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" )
 
P

Peter Hansen

Tim said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,234
Messages
2,571,178
Members
47,809
Latest member
Adisty

Latest Threads

Top