Python f.write() is not taking more arguments

拜拜、爱过 提交于 2021-02-08 05:51:46

问题


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)

This returns the output as

  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.


回答1:


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

Edit:

Regarding you recent comments, you have two options.

Creating an initial dictionary:

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

f.close()

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



回答2:


Use f.writelines(): https://docs.python.org/3/library/io.html#module-io

f.writelines([a,b,c])

No line-separator is added.

If you want to have a special separator, use "separator".join([str(i) for i in [a,b,c]]) and write this to file via f.write()




回答3:


all the previous are valid ones, and I will try to complete them

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



回答4:


f.write() only takes one argument and write that into your file. If you want to write multiple components, you can use f.writelines([a,b,c]). Also, you can only write string to a file, so make sure to do str(*) for all your variables.




回答5:


All the answers suggested are good. If you want to make it more readable and neat, you can do this as well:

f.write("{a},{b},{c}".format(a=a, b=b, c=c)



回答6:


You can use the % operator

Notice that the substitution variables x, y, z are all in parentheses, which means they are a single tuple passed to the % operator.

a=10+3
b=3+12
c=3+13
f.write("%s %s %s" % (a, b, c))
f.close()

Here is an example that you can execute online.

The code works perfectly.

The output is : 13 15 16



来源:https://stackoverflow.com/questions/47078585/python-f-write-is-not-taking-more-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!