我正在尝试创建一个包含用户名和高分的程序,如果他们已经是用户,他们会更新到新的高分,或者只是添加高分。
我的代码是:
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()
有谁知道如何用文件中的new替换旧文件?
答案 0 :(得分:2)
简单的答案是:这是不可能的。操作系统及其文件操作没有" line"的概念。它们处理二进制数据块。一些像Python的标准库这样的库为读取行提供了一个方便的抽象 - 但它们不允许你处理单独的行。
那么如何解决问题呢?只需打开文件,读取所有行,在适当的位置操纵相关行,然后再次写出整个文件。
$.when.apply($, …)
答案 1 :(得分:1)
我建议您转到保存信息的某种标准格式,例如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
答案 2 :(得分:0)
首先,在
之后b = a.read()
写
a.close()
a = open("data","w")
看看你的位置。