Deleting File Lines in Python

后端 未结 3 566
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 15:17

I am trying to create a program that takes in a username and high score, if they are already a user they update to their new high score or just adds the high score if not.

3条回答
  •  一个人的身影
    2021-01-28 16:12

    The simple answer is: it is impossible. Operating-systems and their file-operations have no notion of "lines". They deal with blocks of binary data. Some libraries such as Python's standard-library put a convenient abstraction for reading lines above this - but they don't allow you to address individual lines.

    So how to solve the problem? Simply by opening the file, reading all lines, manipulating the line in question in place, and then write the whole file out again.

     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()
    

提交回复
热议问题