Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python f.write() is not taking more arguments

Tags:

python

file

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.

like image 415
natarajan physicist Avatar asked Dec 04 '22 21:12

natarajan physicist


2 Answers

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()
like image 76
Ajax1234 Avatar answered Dec 06 '22 10:12

Ajax1234


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

like image 41
MEE Avatar answered Dec 06 '22 09:12

MEE