我正在尝试创建一个接受用户名和高分的程序,如果他们已经是用户,他们会更新到新的高分,或者如果不是,则仅添加高分。
我的代码是:
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()
有谁知道如何用文件中的新内容替换旧内容?
简单的答案是:不可能。操作系统及其文件操作没有“行”的概念。它们处理二进制数据块。一些库(例如 Python 的标准库)为reading上面的行 - 但它们不允许您寻址单独的行。
那么如何解决问题呢?只需打开文件,读取所有行,就地操作有问题的行,然后写入whole再次归档。
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)