首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python-如何在不删除内容的情况下写入文本文件

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

Stack Overflow用户
提问于 2020-04-26 19:26:16
回答 3查看 2.5K关注 0票数 0

我是编程新手,不知道有没有人能帮我。我已经在下面创建了一个程序,使我能够写入文本文件。我还有第三个专栏,叫做flower_quantity。我想知道如何在不覆盖flower_quantity的情况下用下面的代码更新文本文件。

代码语言:javascript
复制
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)
EN

回答 3

Stack Overflow用户

发布于 2020-04-26 19:28:51

with open(path, 'a')会在附加模式下打开你的文件,它不会删除文件的内容,也不会把插入符号放在文件的末尾,所以所有的内容都会添加到文件的末尾。

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

票数 0
EN

Stack Overflow用户

发布于 2020-04-26 19:34:24

在追加模式下打开文件

with open(flower_file,"a+"):

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

这将从上次写入的点追加文件。要从新行追加,应以\n

票数 0
EN

Stack Overflow用户

发布于 2020-04-26 20:15:59

有几种方法可以完成这个任务。

但是按照您已经这样做的方法,您可以在读取文件时只包含数量。代码看起来有点像这样。

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61439897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档