Python将int写入文件

时间:2018-04-21 12:02:00

标签: python python-3.x 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),但它也没有用。也许有人可以告诉我该怎么做,或者读什么来得到答案。

1 个答案:

答案 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;。这是您错误的根源。

您的代码中可能还有许多其他错误:

  • &#34;列表&#34;是Python中的保留字,因此调用变量&#34; list&#34;是不好的做法。尝试使用其他名称,例如_list(或删除变量,因为它似乎没有用作目的)。
  • &#34; del line&#34;删除变量&#34; line&#34;。但是,它不会删除文本文件中的实际行,只会删除包含它的变量。有关如何从文本文件中删除行的信息,请参阅Deleting a specific line in a file (python)
  • 代码中似乎没有f1.close()语句。这是在使用后关闭文件所必需的,否则可能无法保存编辑。

就个人而言,我没有尝试删除行,而是在文本文件中维护一个行列表,并在我去的时候从列表中删除/更改行。然后,在程序结束时,我将从更改行的列表中重写文件。

相关问题