On 02/15/2012 03:12 PM, Rituparna Sengupta wrote:
Hi,
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.
Ritu
.
.
.
i=0
while i<m
r=name[i]
f=open('file'+'%s' %(r), "a")
f.write("whatever"+r) #part outside innermost loop gets printed
j=0
while j<n
f.write("output of loop") #part within innermost loop doesn't get printed
j=j+1
f.close()
i=i+1
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
whatever.
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.
--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list