Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing integer values to a file using out.write()

Tags:

I am generating some numbers(lets say, num) and writing the numbers to output file using outf.write(num).
But compiler 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?

like image 924
newbie555 Avatar asked Jun 22 '12 17:06

newbie555


People also ask

How do you write an integer in a text file in Python?

To write an integer to a file, you just have to open a file in write mode, convert the int to a string with str(), and use the write() function. If you want to add an integer to an existing file and append to the file, then you need to open the file in append mode.

How do you add integers to a file?

Syntax of putw: putw(n, fptr); Where, n is the integer we want to write in a file and fptr is a file pointer.

How do you write numerical values in a file in Python?

Writing numbers to files numbers = range(0, 10) filename = "output_numbers. txt" #w tells python we are opening the file to write into it outfile = open(filename, 'w') for number in numbers: outfile. write(str(number)) outfile. close() #Close the file when we're done!


1 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('%03d\n' % 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.

like image 181
Levon Avatar answered Sep 24 '22 23:09

Levon