[Tutor] Struggling with writing results of loop into txt file
Kent Johnson
kent37 at tds.net
Tue Mar 21 17:50:15 CET 2006
Matt Dempsey wrote:
> I'm using xmltramp to process some U.S. House of Rep. vote data. I can
> get it to print what I want but when I try to write it to a text file I
> had all sorts of problems. Can someone tell me what I'm doing wrong?
>
> for each in range(votes):
> st= str(vd[each].legislator('state'))
> vt= str(vd[each].vote)
> nm= (vd[each].legislator('unaccented-name'))
> pt= str(vd[each].legislator('party'))
> f= file('housevote.txt', 'w')
> if st == 'AZ':
> f.write(nm)
> else:
> pass
> f.close()
There are a couple of problems here. First, you are opening the file
inside the loop. Each time you open the file it starts over, wiping out
what was there before! So move the line f=file(...) to before the for
statement.
Second, you aren't putting any newlines into the file. f.write() will
write just what you ask for - not like print which does some simple
formatting for you. So you might try
f.write(nm)
f.write('\n')
Another alternative is to use print-to-file. You can say
print >>f, nm
This works just like print as far as spaces and newlines, but output
will go to f instead of std out.
>
> Before trying to write it to a file, my loop looked like this:
> for each in range(votes):
> st= str(vd[each].legislator('state'))
> if st == 'AZ':
> print vd[each].legislator('unaccented-name'),
> vd[each].legislator('party'), vd[each].vote
Of course your file-writing code doesn't include all this data.
Kent
More information about the Tutor
mailing list