How to write integer values to a file using out.write()?

Question:

I am generating some numbers (let’s say, num) and writing the numbers to an output file using outf.write(num).

But the interpreter is throwing an error:

    outf.write(num)  
TypeError: argument 1 must be string or read-only character buffer, not int.  

How can I solve this problem?

Asked By: newbie555

||

Answers:

write() only takes a single string argument, so you could do this:

outf.write(str(num))

or

outf.write('{}'.format(num))  # more "modern"
outf.write('%d' % num)        # deprecated mostly

Also note that write will not append a newline to your output so if you need it you’ll have to supply it yourself.

Aside:

Using string formatting would give you more control over your output, so for instance you could write (both of these are equivalent):

num = 7
outf.write('{:03d}n'.format(num))

num = 12
outf.write('%03dn' % num)          

to get three spaces, with leading zeros for your integer value followed by a newline:

007
012

format() will be around for a long while, so it’s worth learning/knowing.

Answered By: Levon

any of these should work

outf.write("%s" % num)

outf.write(str(num))

print >> outf, num
Answered By: Joran Beasley
i = Your_int_value

Write bytes value like this for example:

the_file.write(i.to_bytes(2,"little"))

Depend of you int value size and the bit order your prefer

Answered By: user9269722

Also you can use f-string formatting to write integer to file

For appending use following code, for writing once replace ‘a’ with ‘w’.

for i in s_list:
    with open('path_to_file','a') as file:
        file.write(f'{i}n')

file.close()
Answered By: Mohammed Waseem
f = open ('file1.txt','a') ##you can also write here 'w' for create or writing into file
while True :
    no = int(input("enter a number (0 for exit)"))
    if no == 0 :
        print("you entered zero(0) ....... nnow you are exit  !!!!!!!!!!!")
        break
    else :
        f.write(str(no)+"n")

f.close()
   
f1 = open ('Ass1.txt','r')

print("n content of file :: n",f1.read())

f1.close()
   
Answered By: VISHAKHA AGARWAL
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.