Thursday, March 13

python: replacing strings in file

In perl, this one-liner is easy:
perl -p -i -e 's/replace this/using that/g' filename
"-i" means to write the modified text back to the same file.

When it comes to python, to make the files in line, you will need fileinput to specify inplace=1 .
import fileinput
for line in fileinput.FileInput(filename, inplace=1):
    line=line.replace("replace this","using that")
    print line
Somehow the program generate 2 line breaks in my Windows machine, for each line: \r\n becomes \r\n\r\n.

The other way is to open the same file twice, one for reading, and one for writing:
s = open(filename).read()
s = s.replace('replace this', 'using that')
f = open(filename, 'w')
f.write(s)
f.close()
This is "python way" because s is operated as a set, making the program easy to read, with high run-time efficiency.


Labels: