我有python代码的问题,我不知道该怎么做,因为我是相当新的。
date_now1 = datetime.datetime.now()
archive_date1 = date_now1.strftime("%d.%m.%Y")
f1 = open(archive_date1, "r+")
print("What product do you wish to delete ?")
delate_product = str(input())
for line in f1.readlines():
if delate_product in line:
list = line
ready_product = list.split()
quantity_of_product = int(ready_product[1])
if quantity_of_product == 1:
del line
print("Product deleted")
else:
print("You have {} amounts of this product. How many do you want to delete ?".format(quantity_of_product))
x = int(input())
quantity_of_product = quantity_of_product - x
temporary = "{}".format(quantity_of_product)
print(type(temporary))
f1.write(temporary) in ready_product[1]
我收到了消息
f1.write(temporary) in ready_product[1]
TypeError: 'in <string>' requires string as left operand, not int
当我暂时执行print(type())
时,它会显示字符串。我也尝试了str(quantity_of_product)
,但它也没有用。也许有人可以告诉我该怎么做,或者读什么来得到答案。
答案 0 :(得分:2)
出现错误是因为你要求python找出一个整数是否是&#34;&#34;一个字符串。
f1.write(temporary)的输出是一个整数。要查看此内容,请尝试在错误行之前添加print语句。相比之下,ready_product [1]是一个字符串(即列表中的第二个字符串元素&#34; ready_product&#34;)。
运营商&#34; in&#34;需要两个迭代并返回第一个是&#34;在&#34;第二。例如:
>>> "hello in ["hello", "world"]
>> True
>>> "b" in "a string"
>> False
当Python试图查看整数是否为&#34;&#34;一个字符串,它不能并抛出一个TypeError,说&#34;要求字符串作为左操作数,而不是int&#34;。这是您错误的根源。
您的代码中可能还有许多其他错误:
就个人而言,我没有尝试删除行,而是在文本文件中维护一个行列表,并在我去的时候从列表中删除/更改行。然后,在程序结束时,我将从更改行的列表中重写文件。