【问题标题】:Deleting File Lines in Python在 Python 中删除文件行
【发布时间】:2015-11-14 00:18:50
【问题描述】:

我正在尝试创建一个接受用户名和高分的程序,如果他们已经是用户,他们会更新到新的高分,或者如果不是,则只添加高分。

我的代码是:

try:
    a = open("data", "r+")
except FileNotFoundError:
    a = open("data", "w")
a = open("data", "r+")
b = a.read()
user = input("Username: ")
user2 = list(user)
if user in b:
    old = input("What is your old highscore? ")
    new = input("What is your new highscore? ")
    b2 = b.split()
    for line in b2:
        #Where I want to edit.
        line=line.replace(old, new)
        print(line)

else:
    new = input("What is your highscore? ")
    a.write(user + " " + new + "\n")
a.close()

有谁知道如何在文件中用新的替换旧的?

【问题讨论】:

    标签: python file python-3.5


    【解决方案1】:

    简单的答案是:不可能。操作系统及其文件操作没有“行”的概念。它们处理二进制数据块。一些库(例如 Python 的标准库)在此之上为 阅读 行提供了方便的抽象 - 但它们不允许您处理单个行。

    那么如何解决这个问题呢?只需打开文件,读取所有行,在适当的位置操作有问题的行,然后再次写出整个文件。

     import tempfile
    
     highscore_file = tempfile.mktemp()
    
     with open(highscore_file, "w") as outf:
         outf.write("peter 1000\nsarah 500\n")
    
     player = "sarah"
     score = 2000
    
     output_lines = []
     with open(highscore_file) as inf:
         for line in inf:
             if player in line:
                 # replace old with new line. Don't forget trailing newline!
                 line = "%s %i\n" % (player, score)
             output_lines.append(line)
    
     with open(highscore_file, "w") as outf:
         outf.write("".join(output_lines))
    
    
    
     with open(highscore_file) as inf:
         print inf.read()
    

    【讨论】:

    • 关闭文件后如何访问数据?谢谢
    • 我不明白你的问题。您可以通过打开文件来读取数据。正如我的脚本所示。那么 - 缺少什么?
    • 运行时数据不保存。
    • 什么时候运行?我的代码?然后它会保存。它证明它保存了数据,因为它在最后两行中读入并打印出来,证明将 sarah 的分数更新为 2000 有效。
    【解决方案2】:

    我建议您改用某种标准格式来保存信息,例如 JSON、YAML、XML、CSV、pickle 或其他。然后你需要将文件读取并解析为原生数据结构(在这种情况下可能是dict),修改它(这很简单),然后写回来。

    json 为例(人类可读,非常易于使用):

    import json
    
    # loading data
    try:
        with open("data") as a:
            b = json.load(a) # b is dict
    except FileNotFoundError:
        b = {}
    
    # user 
    name = input("What's your name? ")
    score = int(input("What's your high score? "))
    
    # manipulating data
    b[name] = score
    
    # writing back 
    with open("data", "w") as a:
        json.dump(b, a)
    

    shelve 的示例(不是人类可读的,但非常易于使用):

    import shelve
    
    name = input("What's your name? ")
    score = int(input("What's your high score? "))
    
    with shelve.open("bin-data") as b:
        b[name] = score # b is dict-like
    

    【讨论】:

    • 关于搁置,您将如何使用它来访问数据以便人类可以读取他们的高分?可能吗?谢谢
    • @space482:是的,这很简单。 b 的行为与 dict 非常相似,您可以使用它大多数使用相同的语法来完成常规 dicts 可以做的事情。当我说它不是人类可读的时候,我只是说如果你用纯文本编辑器打开文件,你将无法读取数据。
    • 还有一个问题,抱歉。您将如何从文件中打印出用户名和高分?那可能吗?再次感谢
    • 加载文件的结果是一个字典,一个标准的python数据结构。有很多方法可以对此进行迭代,所有这些都在 python 的文档中进行了详细描述。
    • @deets 感谢您的帮助。
    【解决方案3】:

    先,后

    b = a.read()
    

    a.close()
    a = open("data","w")
    

    看看会带你去哪里。

    【讨论】:

    • 谢谢,1 个问题,现在当我尝试替换高分时,它只是删除数据而不是替换它,有什么想法吗?
    • 是的,看看@deets 的回答;我的回答可能使您达到了只写一行的地步,而您必须让代码重新编写所有内容,替换一行。
    猜你喜欢
    • 2014-12-14
    • 1970-01-01
    • 2023-02-08
    • 2015-06-25
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多