SSH
SSH

Reputation: 73

Python : how to write a the value of certain key into a file?

i have a list named "list". it contains two dictionaries.I am accessing these dictionaries as dict[count], dict[count+1].

Now i have to check a key is as version. Then i wrote the code as

filename = "output.txt"
fo = open(filename, "a")
for key1,key2 in zip(dict[count].keys(),dict[count+1].keys()):
   if key1 == 'version':
      # print "value of version:", (dict[count])[key]
      fo.write("value of version:",(dict[count])[key])
   if key2 == 'version':
      # print "value of version:", (dict[count+1])[key]
      fo.write ("value of version:", (dict[count+1])[key2])

Here i am able to print the value of version but i am unable to write into a file.

Errror: TypeError: function takes exactly 1 argument (2 given)

Upvotes: 0

Views: 70

Answers (2)

Gopal Venu
Gopal Venu

Reputation: 27

fo.write() function must have only one argument. You provided two arguments so it did not work. Please see below line and use it.

fo.write("value of version:%s"%(dict[count])[key])
fo.write ("value of version:%s"%(dict[count+1])[key2])

Upvotes: 3

Anand S Kumar
Anand S Kumar

Reputation: 90929

You cannot do file.write() like you do print() passing in multiple objects to print separated by comma (as a tuple) , and that is the reason you are getting the error . You should use string.format() to format your string correctly.

Example -

filename = "output.txt"
fo = open(filename, "a")
for key1,key2 in zip(dict[count].keys(),dict[count+1].keys()):
   if key1 == 'version':
      # print "value of version:", (dict[count])[key]
      fo.write("value of version:{}".format(dict[count][key1]))
   if key2 == 'version':
      # print "value of version:", (dict[count+1])[key]
      fo.write ("value of version:()".format(dict[count+1][key2]))

Also, not sure why you need to do zip and all, you can simply do -

filename = "output.txt"
fo = open(filename, "a")
if 'version' in dict[count]:
    fo.write("value of version:{}".format(dict[count]['version']))
if 'version' in dict[count+1]:
    fo.write("value of version:{}".format(dict[count+1]['version']))

Upvotes: 1

Related Questions