【发布时间】:2020-05-04 09:18:35
【问题描述】:
我正在尝试将布尔值添加到文本文件但收到此错误:
Traceback (most recent call last):
File "/Users/valentinwestermann/Documents/La dieta mediterranea_dhooks.py", line 32, in <module>
f.write(variant["available"])
TypeError: write() argument must be str, not bool
有人知道如何解决这个问题吗? :) 它应该用作补货监视器,并在机器人启动时制作产品可用性的文本版本,然后不断比较它并通知用户产品补货。
import bs4 as bs
import urllib.request
import discord
from discord.ext import commands
from dhooks import Webhook
import requests
import json
r = requests.get("https://www.feature.com/products.json")
products = json.loads((r.text))["products"]
for product in products:
print("============================================")
print(product["title"])
print(product["tags"])
print(product["published_at"])
print(product["created_at"])
print(product["product_type"])
for variant in product["variants"]:
print(variant['title'])
print(variant['available'],"\n")
data =("available")
with open("stock_index.txt","w") as f:
for product in products:
for variant in product["variants"]:
if variant['available'] == True:
f.write(product["title"])
f.write(variant['title'])
print(variant["available"])
f.write("--------------------")
【问题讨论】:
-
您的错误消息表明存在涉及
f.write(variant["available"])的错误,但您的代码不包含任何类似的指令。另外请不要使用if variant['available'] == True来测试布尔值是真还是假。一个简单的if variant['available']:就足够了 -
谢谢 :) 更好,因为它使用更少的代码,对吧? @Sorix
-
这是测试布尔值的推荐方法。看看这个问题和经过验证的答案stackoverflow.com/questions/50816182/…
标签: python boolean text-files shopify monitoring