【问题标题】:Is there a way to directly edit a certain text file line through the OS module? (Python 3.7)有没有办法通过 OS 模块直接编辑某个文本文件行? (Python 3.7)
【发布时间】:2020-01-24 15:19:25
【问题描述】:

我正在尝试制作一个游戏,您的分数会保存为文本文件。得分(点击次数)必须始终位于第二行并按用户保存。每次用户保存时,我希望将文本文件的第二行替换为新的分数。

我尝试过使用堆栈溢出时建议的大量内容,例如 os.replace 或 os.resub,但没有任何效果。

def save():
    global userlog
    global clicks
    score = open(directory + "/" + userlog + ".txt", "r+")
#### On this line, I want some code that will replace the second line in the text file listed above.
    for i in range(random.randint(2,5)):
        print("Saving")
        time.sleep(0.10)
        print("Saving.")
        time.sleep(0.10)
        print("Saving..")
        time.sleep(0.10)
        print("Saving...")
        time.sleep(0.10)
    print("\nGame Saved Sucessfully!")

我没有任何工作。只是收到一些标准错误消息。

任何帮助将不胜感激:)

谢谢:)

【问题讨论】:

  • 没有,据我所知。刚刚有一个类似的问题here。您可以做的是将文本加载到变量中,在保存时编辑变量,将变量写回文本文件。甚至不需要os
  • 但我想稍后在程序中读取第二行,并且不能在保存时继续添加得分。我需要一些代码,在单击保存时将第二行设置为 (clicks)。
  • 澄清:我的意思是如果调用了“保存”操作,则编辑变量。所以你的save() 函数必须包括:加载日志文件、编辑加载的数据、将数据写回日志文件(覆盖现有的或创建新的)。
  • 顺便说一下,os.replace 重命名文件,请参阅here(向下滚动一点)。我会说有点误导;-)
  • 哦,哇,这实际上可能非常有用:)

标签: python-3.x function file operating-system


【解决方案1】:

我的评论说明 - 你的保存功能可以做类似的事情

# load previously logged information
with open(logfile, 'r') as fobj:
    log = fobj.readlines()

# replace line 2 with some new info
log[1] = 'some new info\n'

# overwrite existing logfile        
with open(logfile, 'w') as fobj:
    for line in log:
        fobj.write(line)

原则上,您也可以在r+ 模式下使用open(),正如您在问题中所写的那样。这将要求您使用seek()(参见例如here)来获取指向您要写入的位置的文件指针 - 我不推荐使用更复杂的选项。

【讨论】:

  • 这正是我所需要的!太感谢了。澄清一下,“fobj”是什么意思?我还是 python 的婴儿 :p 你不是我们应得的英雄。你是我们需要的英雄队长;-;
  • @JJKenna:我使用fobj 作为“文件对象”的缩写形式——这就是open() 返回的内容(参见例如here)。有关with 声明的更多信息,例如here - 只是为您完成垃圾收集(.close() 等)的一种便捷方式。
  • 感谢您的解释。这对我来说很有意义。 :)
  • 我收到了这个错误,我不认为它太严重,并且可以修复。你能检查一下有什么问题吗? python line 19, in save log[1] = clicks IndexError: list assignment index out of range 我当前的代码是python def save(): global userlog global clicks with open(directory + "/" + userlog + ".txt", "r") as fobj: log = fobj.readlines() log[1] = clicks with open(directory + "/" + userlog + ".txt", "w") as fobj: for line in log: fobj.write(line)
  • @JJKenna 如果您无法在索引 1 处访问 log,您的日志文件似乎不包含超过一行。打印 log 进行调试,如果您写入文件,请不要不要忘记添加新行 '\n' - 否则,.readlines() 将不知道重新加载文件时行的结束位置。
猜你喜欢
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
  • 2017-02-25
  • 1970-01-01
  • 2016-03-26
  • 1970-01-01
相关资源
最近更新 更多