How to modify a file 'in place' ?

John Machin sjmachin at
Sat Jul 23 00:34:57 CEST 2005

Elby wrote:
> I'm looking for a the most simple and generic way to modify a file, with the
> possibility of making backups. In fact, I would like to emulate Perl's -i
> option.
> here is a bit of code, to explain it further :
> < code >
> from os import rename
> class Modif_File:
>     def __init__(self, filename, ext='.bak'):
>         old_name = filename + ext
>         new_name = filename
>         rename(new_name,old_name)

Quite apart from unusual ideas about what "old" and "new" mean, you have 
a problem if filename == "foo" and a physical file named "foo.bak" 
exists already.

>         self.old = open(old_name,'r')
> = open(new_name,'w')
>         # methods for getting data are linked to the old file :
>         for attr in ('encoding', 'newlines', 'next', 'read',
>                     'readinto', 'readline', 'readlines', 'seek', 
>                     'tell', 'xreadlines'):
>             setattr(self,attr,getattr(self.old,attr))
>         # methods for putting data are linked to the new one :
>         for attr in ('closed','flush','write', 'writelines'):
>             setattr(self,attr,getattr(,attr))

You seem to be majorly confused between a physical file on disk and a 
file object used for accessing physical files. There is absolutely 
neither need nor usefulness in doing all that getattr/setattr stuff.

Have a look at the documentation for the shutil module. The functions in 
that should do most/all of what you want. Then have a look at the 
*source* for that module -- which will be present on your machine; on 
mine it's C:\Python24\Lib\ -- and see how elementary physical 
file manipulations are done, with no getattr or setattr calls.


More information about the Python-list mailing list