perl to python

Kirk Job-Sluder kirk at eyegor.jobsluder.net
Tue May 11 02:57:06 EDT 2004


On 2004-05-09, Olivier Scalbert <olivier.scalbert at algosyn.com> wrote:
> Hello ,
>
> What is the python way of doing this :
> perl -pi -e 's/string1/string2/' file
> ?

To expand on what others have said, python emphasizes readability over
compactness and obscure shortcuts. The perl "-pi" idiom wraps everything
around a nice ammount of code, and the "-e" idiom wraps some more code.

a script that sort of has some of the same functionality would go
something like this:

#############start bad code##################
#!/usr/local/bin/python
import getopt,sys,os,re 
 
#get your command line options 
#files will be in  
optlist, args = getopt.getopt(sys.argv[1:],'e:')
 
#do the -p loop. 
for filename in args: 
     
    #do the -i "in place" edit. 
    oldfilename = filename+'.bak' 
    os.rename(filename,oldfilename) 

    newfile = open(filename,'w') 
 
    #continue the -p loop 
    for line in open(oldfilename).readlines(): 
        #execute all of the -e statements. 
        for command in optlist: 
            #warning bad mojo here 
            foo=(command[1] % line.rstrip("\n"))
            exec(("line=%s" % foo)) 
            #print line 
        #save to the new file 
        print line
        newfile.write(line + "\n") 
newfile.close()
os.unlink(oldfilename) 


############end bad code##################

The above code runs, but is not very good because I'm not that familiar
with exec statements.  Anyway I've tried to capture what "perl -pi -e"
actually does which is to execute an arbitrary command over every line of an
arbitrary list of files, editing them in place, with a temporary backup
copy.

Then you would call it with something like:
python badscript.py -e 're.sub("foo","bar","%s")' badtest.txt

However this is a place where an implicit loop works great.
You can just do: 
perl -pi -e 's/foo/bar/' filelist  

Or if you hate the perl/sed syntax, there is:
gawk '{gsub("foo", "bar", $0); print > FILENAME}' filelist

Both of these work because perl and awk have mechanisms to implicitly
loop over all the lines in a file.  The python way tends to avoid
implicit loops except for a few cases.




> Thanks
> Olivier



More information about the Python-list mailing list