繁体   English   中英

Python:如何将某些键的值写入文件?

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

我有一个名为“列表”的列表。 它包含两个字典。我正在以dict [count],dict [count + 1]的形式访问这些字典。

现在,我必须检查一个密钥是否为版本。 然后我写的代码为

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

在这里,我可以打印version的值,但无法写入文件。

错误:TypeError:函数正好接受1个参数(给定2个)

fo.write()函数必须只有一个参数。 您提供了两个参数,所以它不起作用。 请参阅下面的行并使用它。

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

您不能像执行print()传递file.write()就像传入多个对象以逗号分隔(作为元组)来打印一样,这就是得到错误的原因。 您应该使用string.format()正确格式化字符串。

范例-

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

另外,不确定为什么需要进行压缩等所有操作,您只需执行以下操作-

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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