在Python中删除文件行 [英] Deleting File Lines in Python

查看:100
本文介绍了在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.

我的代码是:

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?

推荐答案

我建议您使用某些标准格式的保存信息,例如JSON,YAML,XML,CSV,pickle或其他.然后,您需要读取文件并将其解析为本机数据结构(在这种情况下,可能为dict),对其进行修改(这很简单),然后将其写回.

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.

带有 json 的示例(易于阅读,易于使用) :

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)

带有 shelve 的示例(难以理解,但是非常容易使用):

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

这篇关于在Python中删除文件行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆