[英]Python writing int into file
我的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)
,但是效果不佳。 也许有人可以让我知道该怎么做,或者读什么才能得到答案。
出现错误是因为您要python找出整数是否在字符串中。
f1.write(temporary)的输出是整数。 为此,请尝试在错误行之前添加打印语句。 相反,ready_product [1]是字符串(即列表“ ready_product”中的第二个字符串元素)。
运算符“ in”使用两个可迭代对象,并返回第一个是否在第二个“ in”中。 例如:
>>> "hello in ["hello", "world"]
>> True
>>> "b" in "a string"
>> False
当Python尝试查看整数是否在字符串中时,它不会并抛出TypeError,并说“需要字符串作为左操作数,而不是int”。 这是您错误的根源。
您的代码中可能还会出现许多其他错误:
就个人而言,我不会在尝试时删除行,而是会在文本文件中维护行列表,并在执行时从列表中删除/更改行。 然后,在程序末尾,我将从更改的行列表中重写文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.