简体   繁体   中英

Python f.write() is not taking more arguments

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.

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

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

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

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.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM