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

前端 未结 4 642
忘了有多久
忘了有多久 2021-02-05 04:48

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:

         


        
4条回答
  •  既然无缘
    2021-02-05 05:17

    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.

提交回复
热议问题