[英]Python f.write() is not taking more arguments
我有这样的python代码
f=open('nv.csv','a+')
a=10+3
b=3+12
c=3+13
f.write(a,b,c)
这将输出返回为
f.write(a,b,c)
TypeError: function takes exactly 1 argument (3 given)
请帮我解决这个问题。 我希望将每个数据输入到我的文件中。
file.write
接受一个参数,一个字符串。 您必须加入您的值,然后写入该文件。 最后,不要忘记关闭您的文件:
f=open('nv.csv','a+')
a=10+3
b=3+12
c=3+13
f.write("{} {} {}\n".format(a, b, c))
f.close()
如果您稍后要使用多个值,则应使用列表:
s = [13, 15, 16, 45, 10, 20]
f.write(' '.join(map(str, s)))
f.close()
编辑:
关于你最近的评论,你有两个选择。
创建初始字典:
s = {"a":13, "b":15, "c" = 16}
for a, b in s.items():
f.write("{} {}\n".format(a, b))
f.close()
或者,使用带有列表的globals
:
s = [13, 15, 16, 45, 10, 20]
final_data = {a:b for a, b in globals().items() if b in s}
for a, b in final_data.items():
f.write("{} {}\n".format(a, b))
f.close()
使用f.writelines()
: https : f.writelines()
f.writelines([a,b,c])
没有添加行分隔符。
如果你想要一个特殊的分隔符,使用"separator".join([str(i) for i in [a,b,c]])
并通过f.write()
将其写入文件
所有以前都是有效的,我会尽力完成它们
with open('nv.csv','a+') as f:
a = 10 + 3
b = 3 + 12
c = 3 + 13
f.write('{}\n'.format( ','.join(map(str, (a, b, c))) )
f.write()
只接受一个参数并将其写入您的文件。 如果要编写多个组件,可以使用f.writelines([a,b,c])
。 此外,您只能将字符串写入文件,因此请确保为所有变量执行str(*)
。
建议的所有答案都很好。 如果你想让它更具可读性和整洁性,你也可以这样做:
f.write("{a},{b},{c}".format(a=a, b=b, c=c)
您可以使用%运算符
请注意,替换变量x,y,z都在括号中,这意味着它们是传递给%运算符的单个元组。
a=10+3
b=3+12
c=3+13
f.write("%s %s %s" % (a, b, c))
f.close()
这是一个可以在线执行的示例 。
代码完美无缺。
输出为: 13 15 16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.