Python 将多个变量写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16822016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:45:37  来源:igfitidea点击:

Write multiple variables to a file

python

提问by mahmood

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

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

Based on what is stated in this postI 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

采纳答案by cmd

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:

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

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

回答by aldeb

Better use formatthis way:

更好地使用format这种方式:

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

Also there is no need to wrap intwith str.

也不需要intstr.

回答by kindall

This should probably be written as:

这大概应该写成:

f.write("255 170\n")

回答by David Marek

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

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

回答by Mike Müller

You need to supply a tuple:

您需要提供一个元组:

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

回答by Jon Clements

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

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

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

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

然后,对于这种简单的格式化,您可以使用print, for Python 2.x,如下所示:

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

Or, for Python 3.x:

或者,对于 Python 3.x:

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

Otherwise, use .format:

否则,请使用.format

f.write('{} {}'.format(int('0xff', 16), int('0xaa', 16)))