[Tutor] Error writing to file...

Alan Gauld alan.gauld at btinternet.com
Fri Dec 25 23:52:21 CET 2009


"Ken G." <beachkid at insightbb.com> wrote

> the program run fine.  Do I need to convert a numeric random number to a 
> string number?

You need to convert your data to a string if you use a text file,
which is the default. If you open the file with 'wb' you can write
any kind of data to it, but you will have to decode it when you
read it back.

Its usually easier to use a text file and convert to a string when writing.

> import random
> print ("First Group - Write")
> file = open("Numbers.txt","w")

The fact you use 'w' here tells Python you want to write text.

> 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

But, as the error says,  you are passing an int.

If you really want to use a binary file see the File Handling topic in
my tutor for an example.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list