YuweiZhang
YuweiZhang

Reputation: 3

Python : get all the results from a loop , not only the last one?

I am running a loop in python , I want the result of every time printed out to a txt file. But by running my code, only the result in the last time of the loop is printed. How can I get the whole result?

Here is my code:

for tr_list in tw_table.findAll('tr'):
    for p_list in tr_list.findAll('td')[-1].findAll('p'):
        pt=p_list.get_text().encode('utf-8')
    for tag_list in tr_list.findAll('td')[0].findAll('p'):
        tagt=tag_list.get_text().encode('utf-8')
        result = tagt,pt
        result = str(result)
        f = open("output.txt","w")
        f.write(result)
        f.write('\n')
        print result

the output.txt should be multiple lines like :

result:
123
456
789

but the fact is that the output.txt has only the last line:

789

Upvotes: 0

Views: 130

Answers (3)

odedsh
odedsh

Reputation: 2624

when you open the file not in append mode all of its content is wiped clean. Because you open it inside your loop you lose all the content except the last result

    f = open("output.txt","w")
    f.write(result)
    f.write('\n')

You should open the file once. do your loop and close it when done

f = open("output.txt","w")
for tr_list in tw_table.findAll('tr'):
    for p_list in tr_list.findAll('td')[-1].findAll('p'):
        pt=p_list.get_text().encode('utf-8')
    for tag_list in tr_list.findAll('td')[0].findAll('p'):
        tagt=tag_list.get_text().encode('utf-8')
        result = tagt,pt
        result = str(result)
        f.write(result)
        f.write('\n')
f.close()

Upvotes: 3

Vor
Vor

Reputation: 35149

change "w" to "a" in f = open("output.txt","w")

Upvotes: 1

poke
poke

Reputation: 388153

Open the file once and keep the file handle open while iterating:

with open("output.txt", "w") as f:
    for tr_list in tw_table.findAll('tr'):
        for p_list in tr_list.findAll('td')[-1].findAll('p'):
            pt = p_list.get_text().encode('utf-8')
        for tag_list in tr_list.findAll('td')[0].findAll('p'):
            tagt = tag_list.get_text().encode('utf-8')
            result = tagt, pt
            result = str(result)
            f.write(result)
            f.write('\n')
            print result

Upvotes: 2

Related Questions