简体   繁体   中英

How to rewrite one line in a text file? Python 3.7

I am trying to make a relatively simple game that saves all of it's data to .txt files. The text file I have to store account data uses a simple format such as follows:

Username
PIN
Balance
--
Username
PIN
Balance
--

Etc. Etc.

What I want to do is just change the balance value. At the moment, the only way I see to do this is to add each line to a list, change the balance value, then rewrite all of the lines one by one back to the text file.

Is there an easier way to do this? If so, how?

That obviously is a very simple file structure, thus it has it's limitations. You will probably won't notice any performance problems until you have more than tens of thousands of lines. As said in the comments you're gonna need a better tool after that.

If you keep using this method, you don't really need to load everything, and save it back on the disk after updating the values.

You can stream reading the file and write back to a temp file at the same time. Once you come across to the group you need to update, you need to update the Balance value of course. After you're done with updating you can delete the old file and rename the temp file with your actual file.

with open('input.txt') as original, open('output.txt', 'w') as target:
    while True:
        label1 = original.readline()
        pin = original.readline()
        label2 = original.readline()
        balance = original.readline()
        if pin.strip('\n') == 'PIN':
            balance = 'new-balance\n'
        target.writelines([label1, pin, label2, balance])
        if not balance:
            break
# Delete original and rename new file.

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