Deleting File Lines in Python

安稳与你 提交于 2019-12-02 09:51:12

I'd advise you to move to some standard format of saving information, such as JSON, YAML, XML, CSV, pickle or another. Then what you need is to read and parse the file into native data structure (probably dict in the case), modify it (it is trivial), and write it back.

Example with json (human readable, quite easy to use):

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)

Example with shelve (not human-readable, but extremely easy to use):

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

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

First off, after

b = a.read()

write

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

See where that takes you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!