On 12/25/09 15:00, Ken G. wrote:
In writing the following program in creating random numbers and writing
them to the file, I get an type error in writing to file. I have tried
number = random(10,99), number = randint(10.99), and number =
random.random(10,00) and still get various errors of writing to file.
If I were to REM out the file.write(number) and file.write('\n') lines,
the program run fine. Do I need to convert a numeric random number to a
string number?

TIA,

Ken

PROGRAM:

import random
print ("First Group - Write")
file = open("Numbers.txt","w")
for i in range(1,10):
number = random.randint(10,99)
print i, number
file.write(number)
file.write('\n')
file.close()

ERROR MESSAGE:

Traceback (most recent call last):
File "/home/ken/Python 262/random.py", line 8, in <module>
file.write(number)
TypeError: argument 1 must be string or read-only character buffer, not int

Hi Ken,

From the docs if you are using 2.6

[snip]
To write something other than a string, it needs to be converted to a string first:

>>> value = ('the answer', 42)
>>> s = str(value)
>>> f.write(s)

http://docs.python.org/tutorial/inputoutput.html
--
David Abbott (dabbott)
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to