Python将int写入文件

标签 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),但效果不佳。也许有人可以告诉我该做什么,或者读什么才能得到答案。

最佳答案

出现错误是因为您要求 python 找出整数是否在字符串“中”。

f1.write(temporary) 的输出是一个整数。要看到这一点,请尝试在错误行之前添加一条打印语句。相反,ready_product[1] 是一个字符串(即列表“ready_product”中的第二个字符串元素)。

运算符“in”接受两个可迭代对象,并返回第一个可迭代对象是否在第二个可迭代对象中。例如:

>>> "hello in ["hello", "world"]
>> True
>>> "b" in "a string"
>> False

当 Python 尝试查看整数是否在字符串“中”时,它不能并抛出 TypeError,指出“需要字符串作为左操作数,而不是 int”。这是你错误的根源。

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

  • “list”是 Python 中的保留字,因此将变量称为“list”是不好的做法。尝试其他名称,例如 _list(或删除该变量,因为它似乎没有用处)。
  • “del line”删除变量“line”。但是,它不会删除文本文件中的实际行,只会删除包含该行的变量。请参阅Deleting a specific line in a file (python)了解如何从文本文件中删除一行。
  • 代码中似乎没有 f1.close() 语句。使用后必须关闭文件,否则编辑内容可能无法保存。

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

关于Python将int写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49955556/

相关文章:

python - 使用 Scipy.optimize 方法 ='SLSQP' 返回初始猜测

python - Pandas 如何对每一行中连接的字符串进行排序?

python - 使用 Pandas 计算不同子段的 T 统计量

Python 无法安装 PyGObject

Python:检查 "two".doc 文件是否是同一个文件?

windows - 在 Powershell 中删除 file1 中存在于 file2 中的行

Python删除包含 "l"的单词

python - 以整数形式获取 pandas 数据框行的索引

python - 仅在 __attrs_post_init__ 结束后运行属性验证器

python - 在 Bokeh Timeseries 图中,如何指定 line_width?