Take the 2-minute tour ×

Instead on reading each and every line cant we just search for the string in the file and replace it... i am trying but unable to get any idea how to do thth?

file = open(C:\\path.txt,"r+")
lines = file.readlines()
newString="set:: windows32\n"
for l in lines: 
     if (re.search("(address_num)",l,re.I) replaceDone==0:
        except IOError:
share|improve this question
i don;t need to use the for l in lines statement! as it reads the file line by line... if it is a huge file and the its goign to take lot of memory –  user2052617 Feb 26 '13 at 3:55
Well, something's going to have to read through the file somehow to find it - isn't it? :) –  Jon Clements Feb 26 '13 at 3:56
That’s not valid Python, and I don’t think that replace is necessary/doing what you think it does. Could you maybe explain what it is that needs doing in more detail, please? –  minitech Feb 26 '13 at 3:58
@user2052617: You read the file line-by-line to reduce the memory usage. –  Blender Feb 26 '13 at 4:00
What is "thth"? –  Robᵩ Feb 26 '13 at 4:07
show 4 more comments

2 Answers

Here's an example you can adapt that replaces every sequence of '(address_num)' with 'set:: windows32' for a file:

import fileinput
import re

for line in fileinput.input('/home/jon/data.txt', inplace=True):
    print re.sub('address_num', 'set:: windows32', line, flags=re.I),
share|improve this answer
add comment

This is not very memory efficient but I guess it is what you are looking for:

import re
text = open(file_path, 'r').read()
open(file_path, 'w').write(re.sub(old_string, new_string, text))

Read the whole file, replace and write back the whole file.

share|improve this answer
add comment

Your Answer


