Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing lines with elements from a list

Tags:

python

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

like image 624
Finger twist Avatar asked Dec 05 '25 08:12

Finger twist


2 Answers

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.

like image 133
David Robinson Avatar answered Dec 07 '25 20:12

David Robinson


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.

like image 21
asthasr Avatar answered Dec 07 '25 21:12

asthasr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!