如何删除特定的行并在python中替换它

时间:2013-11-12 11:19:52

标签: python

我有一个python游戏,可以将这样的用户数据写入:Bob 3到文本文件。我正在尝试编码所以如果玩家到达某个点,它将删除级别编号(在示例中:1)并写入新级别。我已将此分开:

name, level = line.split()

有没有这样做?

1 个答案:

答案 0 :(得分:1)

“更新”普通文件实际上意味着编写一个新文件,然后用新文件替换旧文件 - 您不能只进行“就地”更新。虽然技术上可行并且不是很困难,但它可能不是满足您需求的最有效解决方案,因为您必须通过整个读取+解析旧文件/为每次更新写入新的/重命名(并且可能必须处理)同时访问也取决于您的应用程序)。使用某种数据库(键/值,关系,文档,等等......)可能是一个更好的解决方案,因为它将负责大部分的内务管理。

对于你的问题的一个非常幼稚的答案,它看起来像这样:

def update_level(username, new_level):
   inpath = "/path/to/your/file"
   outpath = "path/to/tmpfile"
   with open(inpath) as infile:
       with open(outpath, "w") as outfile:
           for line in infile:
               line = line.strip()
               name, level = line.split()
               if name == username:
                   line = " ".join((username, new_level))
               outfile.write("%s\n" % line)
   os.rename(outpath, inpath)