3

I want to write two variable to a file using Python.

Based on what is stated in this post I wrote:

f.open('out','w')
f.write("%s %s\n" %str(int("0xFF",16)) %str(int("0xAA",16))

But I get this error:

Traceback (most recent call last):
  File "process-python", line 8, in <module>
    o.write("%s %s\n" %str(int("0xFF", 16))  %str(int("0xAA", 16)))
TypeError: not enough arguments for format string
Community
  • 1
  • 1
mahmood
  • 21,089
  • 43
  • 130
  • 209
  • is this even syntactically correct? I would think it would have to be `"%s %s\n" % (str(int("0xFF", 16)), str(int("0xAA", 16)))` –  May 29 '13 at 19:15
  • Why are you using `str(int())`, anyway? `"%i %i\n" % (int("0xFF", 16), int("0xAA",16))` would work just as well and, in my opinion, is a bit clearer. Also, if only hexadecimal strings are guaranteed to begin with `0x` then you can use `int(string, 0)`, as that will automatically convert properly-prefixed octal strings and handle decimal strings correctly as well. If all your strings are hex and might not be preceded by `0x` then using `int(string, 16)` is probably how you need to go, though. – JAB May 29 '13 at 20:26

6 Answers6

11

You are not passing enough values to %, you have two specifiers in your format string so it expects a tuple of length 2. Try this:

f.write("%s %s\n" % (int("0xFF" ,16), int("0xAA", 16)))
cmd
  • 5,444
  • 15
  • 29
3

Better use format this way:

'{0} {1}\n'.format(int("0xFF",16), int("0xAA",16))

Also there is no need to wrap int with str.

aldeb
  • 6,014
  • 3
  • 23
  • 47
  • yeah format is nice providing he is using python2.7 or greater – cmd May 29 '13 at 19:18
  • `format` is available in 2.6, although you must explicitly number the replacement fields (i.e., `'{0} {1}\n'.format(...)`). – chepner May 29 '13 at 19:22
2

The % operator takes an object or tuple. So the correct way to write this is:

f.write("%s %s\n" % (int("0xFF", 16), int("0xAA",16)))

There are also many other ways how to format a string, documentation is your friend http://docs.python.org/2/library/string.html

David Marek
  • 549
  • 2
  • 9
2

Firstly, your opening the file is wrong f.open('out', 'w') should probably be:

f = open('out', 'w')

Then, for such simple formatting, you can use print, for Python 2.x, as:

print >> f, int('0xff', 16), int('0xaa', 16)

Or, for Python 3.x:

print(int('0xff', 16), int('0xaa', 16), file=f)

Otherwise, use .format:

f.write('{} {}'.format(int('0xff', 16), int('0xaa', 16)))
Jon Clements
  • 132,101
  • 31
  • 237
  • 267
1

You need to supply a tuple:

f.open('out','w')
f.write("%d %d\n" % (int("0xFF",16), int("0xAA",16)))
Mike Müller
  • 77,540
  • 18
  • 155
  • 159
-1

This should probably be written as:

f.write("255 170\n")
kindall
  • 168,929
  • 32
  • 262
  • 294