When writing to a file, you must write strings but you are trying to write a floating point value. Use str()
to turn those into strings for writing:
c.write(str(count))
Note that your c.close
line does nothing, really. It refers to the .close()
method on the file object but does not actually invoke it. Neither would you want to close the file during the loop. Instead, use the file as a context manager to close it automatically when you are d one. You also need to include newlines, explicitly, writing to a file does not include those like a print
statement would:
with open("text.txt","w") as c:
count = 0
while count < 100:
print count
count += 0.1
c.write(str(count) + '\n')
Note that you are incrementing the counter by 0.1, not 1, so you are creating 10 times more entries than your question seems to suggest you want. If you really wanted to only write integers between 1 and 999, you may as well use a xrange()
loop:
with open("text.txt","w") as c:
for count in xrange(1, 1000):
print count
c.write(str(count) + '\n')
count = count + 1
, in any case? – chepner Jul 15 '13 at 12:35