perl to python

Jason Mobarak jmob at spam__unm.edu
Mon May 10 11:14:02 EDT 2004


John Roth wrote:
> "Olivier Scalbert" <olivier.scalbert at algosyn.com> wrote in message
> news:409e86e9$0$22811$a0ced6e1 at news.skynet.be...
> 
>>Hello ,
>>
>>What is the python way of doing this :
>>perl -pi -e 's/string1/string2/' file
>>?
>>Thanks
>>Olivier
> 
> 
> I'm not sure what the -pi and -e switches do, but the
> rest is fairly simple, although not as simple as the perl
> one-liner.
> 
> Just load the file into a string variable, and either
> use the string .replace() method, or use a regx,
> depending on which is appropriate. Then write
> it back out.
> 
> from the python prompt (not the command prompt)
> that's something like: (untested)
> 
> var = open("file", "r").read().replace("string1", "string2")
> open("file", "w").write(var)
> 
> I think this is about as obfusticated as you can get -
> you'll lose the file if you try for a one-liner.
> 
> John Roth
> 

More obfuscated:

python -c '(lambda fp: fp.write(fp.seek(0) or 
"".join([L.replace("th","ht") for L in fp])))(file("foo","rw+"))'




More information about the Python-list mailing list