簡體   English   中英

Python-如何在不刪除內容的情況下寫入文本文件

[英]Python- how to write to text file without deleting contents

我是編程新手,想知道是否有人可以幫助我。 我在下面創建了一個程序,使我能夠寫入文本文件。 我有第三列,名為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)

with open(path, 'a')將以 append 模式打開您的文件,該模式不會刪除內容並將插入符號放在文件末尾,因此所有內容都將添加到文件末尾。

您可以找到所有可用文件打開模式的許多評論,例如https://stackabuse.com/file-handling-in-python/

以append模式打開文件

with open(flower_file,"a+"):

如果文件不存在, +號會創建一個新文件

這將從文件的最后寫入點開始 append 文件。 從新行到 append,你應該從 \n 開始

有幾種方法可以完成這項工作。

但是按照您已經這樣做的方式,您可以在讀取文件時僅包含數量。 代碼看起來有點像這樣。

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+')打開文件。 並導航到您想要 append 的指定行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM