简体   繁体   English

如何用Python重写文件中的行?

[英]How to rewrite lines in a file in Python?

I am extremely new to coding and barely have any idea what I'm doing when it comes to file i/o. 我对编码非常陌生,几乎不了解文件I / O的工作方式。 I was wondering if there was a way that I could overwrite a line in a text file I've opened. 我想知道是否有一种方法可以覆盖我打开的文本文件中的一行。

Specifically, I'm making an extremely basic text game. 具体来说,我正在做一个非常基础的文字游戏。 The point is not the game though, it's for me to get used to file i/o. 关键不是游戏,而是我习惯于提交I / O。 In essence I am trying to keep track of the total number of correct and incorrect guesses a player has made. 本质上,我试图跟踪玩家做出的正确和错误猜测的总数。 In order to do this, I created a file where the first line would hold a number with their correct guesses, and the second line would hold a number with their incorrect guesses. 为此,我创建了一个文件,其中第一行将包含带有正确猜测的数字,第二行将包含带有错误猜测的数字。 I need to be able to rewrite these lines, however, in order to update them every game. 我需要能够重写这些行,以便在每个游戏中更新它们。

Essentially I am just wondering if there is anything similar to .readline() or anything I can do with .readline() in order to replace the first and second line of a text file. 本质上,我只是想知道是否有类似于.readline()的东西,或者我可以对.readline()进行任何操作以替换文本文件的第一行和第二行。

Any help would be greatly appreciated! 任何帮助将不胜感激!

PS Please try to keep in mind, I am an absolute beginner, therefore the simpler the strategy, the better. PS:请记住,我是一个绝对的初学者,因此策略越简单越好。 Thanks! 谢谢!

Read all data from file at the beginning and write all data when you need it. 首先从文件中读取所有数据,并在需要时写入所有数据。
Especially at the end of game. 特别是在比赛结束时。 It is easer. 容易些。

You can use JSON format because it is easy to convert from text file into python dictionary 您可以使用JSON格式,因为它很容易从文本文件转换为python字典

import json

data = {
  'correct': 7,
  'incorrect': 8
}

# write data

f = open('config.txt', 'w')
json.dump(data, f)
f.close()

data['correct'] = 100
print data['correct']  # 100

# read data

f = open('config.txt', 'r')
data = json.load(f)
f.close()

print data['correct']  # 7

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

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