简体   繁体   English

在Python中删除文件行

[英]Deleting File Lines in Python

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. 我正在尝试创建一个接受用户名和高分的程序,如果他们已经是用户,则将其更新为新的高分,如果没有,则添加高分。

My code is: 我的代码是:

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

Does anyone know how to replace the old with the new in the file? 有谁知道如何用文件中的新文件替换旧文件?

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. 诸如Python的标准库之类的某些库为读取上面的行提供了便利的抽象-但它们不允许您处理单个行。

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

I'd advise you to move to some standard format of saving information, such as JSON, YAML, XML, CSV, pickle or another. 我建议您使用某种标准格式的保存信息,例如JSON,YAML,XML,CSV,pickle或其他格式。 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. 然后,您需要读取文件并将其解析为本机数据结构(在这种情况下可能是dict ),对其进行修改(这很琐碎),然后将其写回。

Example with json (human readable, quite easy to use): 带有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)

Example with shelve (not human-readable, but extremely easy to use): shelve示例( 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

First off, after 首先,之后

b = a.read()

write

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

See where that takes you. 看看带你去哪里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM