【问题标题】:Save list output after filtering onto text file过滤到文本文件后保存列表输出
【发布时间】:2019-11-14 06:17:09
【问题描述】:

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

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

【问题讨论】:

    标签: python list file text


    【解决方案1】:

    正如错误所说,f.write() 只接受一个参数,但你给它三个。你可以这样做:

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

    【讨论】:

      【解决方案2】:

      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 兼容吗?
      • 抱歉不知道您使用的是 2.7,F-string 在 python 3.6 中引入并使用相同的版本及更高版本,在您的情况下格式应该是这种情况,所以我更新了答案。
      • 您的解决方案应运行 v3.6 及更高版本,因为它使用 f-string。感谢分享并感谢您的支持。这个答案很有用。谢谢
      猜你喜欢
      • 2021-12-09
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多