简体   繁体   中英

Python- how to write to text file without deleting contents

I am new to programming and was wondering if anyone can help me. I have created a program below that enables me to write to the text file. I have a third Column called flower_quantity. I was wondering how I can update the text file with the code below without overwriting the 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') will open your file in append mode, which will not delete contents and put the caret at end of file, so everything will be added at end of file.

You can find many reviews of all available file-opening modes, for example https://stackabuse.com/file-handling-in-python/

Open the file in append mode

with open(flower_file,"a+"):

the + sign creates a new file if the file is not already present

this will append the file from its last written point. To append from a new line, you should start with \n

There are a couple of ways to get this one done.

But following the way you have already been doing it, you could just include quantity when reading the file. The code would look a little like this.

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)

Alternatively if you did want to update and not overwrite the entire file, you would need to open the file with open('txtfile.txt','a+') . and navigate to the specified line that you would like to append.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM