writing to a file from within nested loops
d at davea.name
Wed Feb 15 15:36:31 EST 2012
On 02/15/2012 03:12 PM, Rituparna Sengupta wrote:
> I'm working on this code and I keep getting an error. It might be some very basic thing but I was wondering if someone could help. Its a loop within a loop. The part outside the innermost loop gets printed fine, but the part within the innermost loop doesn't get printed. I get an error: 'str' has no attribute 'write'. Thanks in advance.
> while i<m
> f=open('file'+'%s' %(r), "a")
> f.write("whatever"+r) #part outside innermost loop gets printed
> while j<n
> f.write("output of loop") #part within innermost loop doesn't get printed
Welcome to the mailing list.
Some fundamentals, please:
1) give python version & os
2) copy/paste the code, don't retype it. You have lots of typos which
would cause syntax errors, not "xxx" has no attribute "yyy". And please
don't use 1 column indents; they're illegible. 4 spaces is a good
number, recommended in a large number of places, including pep8.
3) copy/paste the whole error, including traceback. Without it in this
case, we're forced to guess where the problem might be, and that must be
somewhere else in the program, since the only write() attribute you've
quoted here are on f.write() calls, and f is only set to a file object,
not a string object. There are lots of ways in the code you don't show,
where you might confuse the system, such as redefining open.
Now to your questions:
A) Since you don't show n, it could very well be 0 or negative, in which
case the inner loop would never execute.
B) Since you don't have correct indentation, it's possible the actual
program closes the file inside the inner loop, in which case it might
execute just once, then get an exception. not the one you quote, but
C) Depending on how you run this program, perhaps the file isn't getting
flushed when you get your error, so you just think the output didn't happen.
D) BTW, i don't see any prints, but perhaps that's a minor point. You
might think of file.write() as printing to a file. Sort of.
More information about the Python-list