python equivalent to perl's inplace edit mechanism
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Thu May 8 08:44:34 EDT 2008
En Thu, 08 May 2008 09:11:56 -0300, Michael Mabin <d3vvnull at gmail.com> escribió:
> Does python have an equivalent to Perl's inplace-edit variable $^I?
> For example, the following perl code below changes mike to dave in a file
> that is passed as an argument.
>
> #!/usr/bin/env perl
> #chgit script
> $^I = '';
> while(<>) {
> s/mike/dave/g;
> print;
> }
>
> The script would be used as below:
> chgit somefile
>
> Afterward, all instances of mike are changed to dave.
Like this?
<code>
import sys,fileinput
for line in fileinput.input(inplace=True):
sys.stdout.write(line.replace('mike','dave'))
</code>
Sample session:
C:\TEMP>type foo.txt
this line tells about mike and john
this second line says nothing
goodbye mike!
C:\TEMP>python chgit.py foo.txt
C:\TEMP>type foo.txt
this line tells about dave and john
this second line says nothing
goodbye dave!
--
Gabriel Genellina
More information about the Python-list
mailing list