Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 过滤到文本文件后保存列表输出_Python_List_File_Text - Fatal编程技术网

Python 过滤到文本文件后保存列表输出

Python 过滤到文本文件后保存列表输出,python,list,file,text,Python,List,File,Text,我想将下面的输出列表保存到文本文件中 with open("selectedProd.txt", 'w') as f: for x in myprod["prod"]: if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" : f.write(x["name"],x["id"], x["price"]) 我犯了个错误 f.write(x["name"],x["id"],

我想将下面的输出列表保存到文本文件中

with open("selectedProd.txt", 'w') as f:
   for x in myprod["prod"]:
      if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
         f.write(x["name"],x["id"], x["price"])
我犯了个错误

f.write(x["name"],x["id"], x["price"])
TypeError: function takes exactly 1 argument (3 given)
预期的文本文件输出如下

item1 111 2.00
item2 222 5.00
item3 444 1.00
item4 666 5.00
item5 212 7.00
请进一步建议。谢谢


下面的两种解决方案都适用于上面的python2.7和python3.6,正如错误所说,
f.write()
只接受一个参数,但您给它三个参数。相反,您可以执行以下操作:

f.write("{} {} {}".format(x["name"],x["id"],x["price"]))

正如错误所说,
f.write()
只接受一个参数,但您要给它三个参数。相反,您可以执行以下操作:

f.write("{} {} {}".format(x["name"],x["id"],x["price"]))

wirte
函数只接受一个参数,因此您必须将参数转换为一个字符串,并一次传递一个

with open("selectedProd.txt", 'w') as f:
   for x in myprod["prod"]:
      if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
         # for string convertion I used f-strings
         context = '{} {} {}'.format(x["name"], x["id"], x["price"])
         f.write(context)

wirte
函数只接受一个参数,因此您必须将参数转换为一个字符串,并一次传递一个

with open("selectedProd.txt", 'w') as f:
   for x in myprod["prod"]:
      if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
         # for string convertion I used f-strings
         context = '{} {} {}'.format(x["name"], x["id"], x["price"])
         f.write(context)

谢谢你的意见和建议。。。但我在运行python 2.7时遇到语法错误…它与2.7兼容吗?很抱歉,我不知道您正在使用python 3.6中引入的2.7,F-string,并使用相同版本及更高版本,在您的案例格式中应该是如此,因此我更新了答案。您的解决方案将运行v3.6及更高版本,因为它使用F-string。感谢分享并感谢您的支持。这个答案很有用。感谢您的意见和建议。。。但我在运行python 2.7时遇到语法错误…它与2.7兼容吗?很抱歉,我不知道您正在使用python 3.6中引入的2.7,F-string,并使用相同版本及更高版本,在您的案例格式中应该是如此,因此我更新了答案。您的解决方案将运行v3.6及更高版本,因为它使用F-string。感谢分享并感谢您的支持。这个答案很有用。谢谢