I am reading a file and looking for a particular string in it like this :
template = open('/temp/template.txt','r')
new_elements = ["movie1","movies2"]
for i in template.readlines():
if "movie" in i:
print "replace me"
This is all good but I would like to replace the lines that are found with the elements from "new_elements" . I make the assumption that the number of found strings will always match the number of elements in the "new_elements" list . I just don't know how to iterate over the new_elements whilst looking for lines to replace .
Cheers
One way is to make new_elements an iterator:
template = open('/temp/template.txt','r')
new_elements = iter(["movie1","movies2"])
for i in template.readlines():
if "movie" in i:
print "replace line with", new_elements.next()
You haven't said how you want to do the replacement- whether you want to write it to a new file, for example- but this will fit into whatever code you use.
What you're looking for is pretty simple: the .pop() method of lists. This will get the next entry in the list, and remove it; your next call to that function will return the next item. No need to do any iteration at all.
Without a parameter, it will pop the last element. If you want to pop the first, you can use new_elements.pop(0), although this will be slower than popping from the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With