replace string in a file
Unknown
cantabile.03 at wanadoo.fr
Sun Mar 16 22:03:41 EDT 2008
Le Sat, 15 Mar 2008 16:55:45 -0700, joep a écrit :
> you can also use standard module fileinput.input with ''inplace'' option
> which backs up original file automatically.
>
> from python help for fileinput:
>
> Optional in-place filtering: if the keyword argument inplace=1 is passed
> to input() or to the FileInput constructor, the file is moved to a
> backup file and standard output is directed to the input file (if a file
> of the same name as the backup file already exists, it will be replaced
> silently).
Thanks for the idea :)
What I do not get is how I can replace a string with that.
If I write something like:
for line in filehandle.input('myfile.txt', inplace=1):
rx = re.match(r'^\s*(\d+).*',line )
if not rx:
continue
else:
oldValue = rx.group(1)
Value = 123456789
line = string.replace(line, oldValue, "%d" Value)
print line
break
This code replaces the whole file with line, instead of replacinf the old
value with the new one. Did I forget something ?
More information about the Python-list
mailing list