简体   繁体   English

如何重写文本文件中的一行? 蟒蛇 3.7

[英]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.我正在尝试制作一个相对简单的游戏,将所有数据保存到 .txt 文件中。 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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