Python f.write()没有接受更多参数 [英] Python f.write() is not taking more arguments

查看:71
本文介绍了Python f.write()没有接受更多参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的python代码

I am having a python code like this

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)

请帮助我解决此问题.我希望将所有数据输入到我的文件中.

Kindly help me to solve this problem. I wish to enter every data into my file.

推荐答案

file.write 采用单个参数,即字符串.您必须加入您的值,然后将其写入文件.最后,不要忘记关闭文件:

file.write takes a single parameter, a string. You have to join your values and then write to the file. Lastly, do not forget to close your file:

f=open('nv.csv','a+')
a=10+3
b=3+12
c=3+13
f.write("{} {} {}\n".format(a, b, c))
f.close()

如果以后要使用多个值,则应使用列表:

If you are going to multiple values later on, you should use a list:

s = [13, 15, 16, 45, 10, 20]
f.write(' '.join(map(str, s)))
f.close()

关于您最近的评论,您有两种选择.

Regarding you recent comments, you have two options.

创建初始词典:

s = {"a":13, "b":15, "c" = 16}
for a, b in s.items():
   f.write("{} {}\n".format(a, b))

f.close()

或者,将 globals 与列表一起使用:

Or, using globals with a list:

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()

这篇关于Python f.write()没有接受更多参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆