Reputation: 61
I have file test.html
<p>Just example code</p>
<div>
<img src="http:localhost/img1.jpg">
</div>
<p>Just example code2</p>
<div>
<img src="http:localhost/img1.jpg">
</div>
<p>Just example code3</p>
<div>
<img src="http:localhost/img1.jpg">
</div>
and i wanna with test.python replace in file just string with "img1.jpg" to "img2","img3" etc.
import string
s = open("test.html").read()
s = s.replace('http:localhost/img1.jpg','http:localhost/img2.jpg')
f = open("test2.html", 'w')
f.write(s)
f.close()
but program replace all img1 when i wanna replace all string img1 to img2,img3,img[i+1].
How to do it?
Upvotes: 1
Views: 44
Reputation: 417
Assuming what you need is a new file with img1 changed to img1 , img2 , img3 .. so on . The following code should work . You will have to go one line at a time .
i=2
with open("test.html")as f ,open("test2.html",'w') as f1:
for elem in f.readlines():
if 'http:localhost/img' in elem:
f1.write(elem.replace('http:localhost/img1','http:localhost/img%s'%i))
i+=1
else:
f1.write(elem)
Upvotes: 0
Reputation: 670
You can do:
s = s.replace('http:localhost/img1.jpg','http:localhost/img2.jpg',1)
The third param is the max ocurrences to replace.
You can see it in python documentation
Upvotes: 1