繁体   English   中英

Python将int写入文件

[英]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”。 这是您错误的根源。

您的代码中可能还会出现许多其他错误:

  • “列表”是Python中的保留字,因此将变量“列表”称为不好的做法。 尝试使用其他名称,例如_list(或删除变量,因为它似乎没有作用)。
  • “ del line”删除变量“ line”。 但是,它不会删除文本文件中的实际行,只会删除包含它的变量。 有关如何从文本文件中删除行的信息,请参见删除文件中的特定行(python)
  • 代码中似乎没有f1.close()语句。 使用后关闭文件是必要的,否则可能无法保存编辑。

就个人而言,我不会在尝试时删除行,而是会在文本文件中维护行列表,并在执行时从列表中删除/更改行。 然后,在程序末尾,我将从更改的行列表中重写文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM