Python-如何在不删除内容的情况下写入文本文件

问题描述 投票:0回答:3

我不熟悉编程,想知道是否有人可以帮助我。我在下面创建了一个程序,使我能够写入文本文件。我有第三个专栏,名为flower_quantity。我想知道如何在不覆盖flower_quantity的情况下使用以下代码更新文本文件。

def feature_4(flower_file='flowers.txt'):

    flower_update = input("Enter the name of the flower you wish to change the price:"
                          "Lily, Rose, Tulip, Iris, Daisy, Orchid, Dahlia, Peony")
    flower_new_price = input("Enter the updated price of the flower")

    flower, price = [], []
    with open(flower_file) as amend_price:

        for line in amend_price:
            spt = line.strip().split(",")
            flower_price = int(spt[1])
            flower_name = str(spt[0])

            if flower_name == flower_update :
                price.append(flower_new_price)

            else:
                price.append(flower_price)

            flower.append(flower_name)

    with open(flower_file, "w") as f_:
        for i, v in enumerate(flower):
            f_.write("{},{}\n".format(v, str(price[i])))

    print("The new price of", flower_update, "is", flower_new_price)
python python-3.x python-2.7 text-files
3个回答
0
投票

[with open(path, 'a')将以附加模式打开文件,不会删除内容并将插入号放在文件末尾,因此所有内容都会添加到文件末尾。

您可以找到所有可用文件打开模式的许多评论,例如https://stackabuse.com/file-handling-in-python/


0
投票

有两种方法可以完成此任务。

但是按照您已经做过的方式,您可以在读取文件时仅包括数量。代码看起来像这样。

def feature_4(flower_file='flowers.txt'):

    flower_update = input("Enter the name of the flower you wish to change the price:"
                          "Lily, Rose, Tulip, Iris, Daisy, Orchid, Dahlia, Peony")
    flower_new_price = input("Enter the updated price of the flower")

    flower, price, quantity = [], [], []
    with open(flower_file) as amend_price:

        for line in amend_price:
            spt = line.strip().split(",")
            flower_price = int(spt[1])
            flower_name = str(spt[0])
            quantity.append(str(spt[2]))

            if flower_name == flower_update :
                price.append(flower_new_price)

            else:
                price.append(flower_price)

            flower.append(flower_name)

    with open(flower_file, "w") as f_:
        for i, v in enumerate(flower):
            f_.write("{},{},{}\n".format(v, str(price[i]),quantity[i]))

    print("The new price of", flower_update, "is", flower_new_price)

或者,如果您确实要更新而不是覆盖整个文件,则需要使用open('txtfile.txt','a+')打开文件。并导航到要添加的指定行。


0
投票

以追加模式打开文件

with open(flower_file,"a+"):

+符号会创建一个新文件,如果该文件尚不存在

这将从文件的最后写入点开始追加。要从新行追加,请以\ n

开头
© www.soinside.com 2019 - 2024. All rights reserved.