'How to write integer values to a file using out.write()?
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?
Solution 1:[1]
any of these should work
outf.write("%s" % num)
outf.write(str(num))
print >> outf, num
Solution 2:[2]
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
Solution 3:[3]
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()
Solution 4:[4]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | joaquin |
| Solution 2 | Leonardo Alves Machado |
| Solution 3 | Paul Roub |
| Solution 4 | VISHAKHA AGARWAL |
