How to modify a file 'in place' ?
sjmachin at lexicon.net
Sat Jul 23 00:34:57 CEST 2005
> 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
> 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
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"
> self.old = open(old_name,'r')
> self.new = 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'):
> # methods for putting data are linked to the new one :
> for attr in ('closed','flush','write', 'writelines'):
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\shutil.py -- and see how elementary physical
file manipulations are done, with no getattr or setattr calls.
More information about the Python-list