3

我想使用 Python 将两个变量写入文件。

根据这篇文章中所说的,我写道:

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

但我得到这个错误:

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
4

6 回答 6

11

您没有向 传递足够的值%,您的格式字符串中有两个说明符,因此它需要一个长度为 2 的元组。试试这个:

f.write("%s %s\n" % (int("0xFF" ,16), int("0xAA", 16)))
于 2013-05-29T19:13:49.143 回答
3

更好地使用format这种方式:

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

也不需要intstr.

于 2013-05-29T19:14:36.883 回答
2

% 运算符接受一个对象或元组。所以正确的写法是:

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

还有很多其他方法可以格式化字符串,文档是你的朋友http://docs.python.org/2/library/string.html

于 2013-05-29T19:17:22.860 回答
2

首先,您打开文件错误f.open('out', 'w')应该是:

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

然后,对于这种简单的格式,您可以使用printPython 2.x 的 , 为:

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

或者,对于 Python 3.x:

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

否则,使用.format

f.write('{} {}'.format(int('0xff', 16), int('0xaa', 16)))
于 2013-05-29T19:25:38.653 回答
1

您需要提供一个元组:

f.open('out','w')
f.write("%d %d\n" % (int("0xFF",16), int("0xAA",16)))
于 2013-05-29T19:17:39.813 回答
-1

这大概应该写成:

f.write("255 170\n")
于 2013-05-29T19:15:59.627 回答