我有一个我正在创建的扫雷游戏的高分文件,并且每次添加新分数后,我希望它按每个分隔线排序。
我正在使用:
def save_score(score):
name = input("type a name")
file = open("highscores.txt", "a")
file.write("Table: "+str(GRID_TILES)+"x"+str(GRID_TILES)+"\t mode:"+str(Dif)+"\t score:"+str(score)+"\t name:"+str(name)+"\n")
file.close()
以这种格式出现:
table: 10x10 mode: easy score: 7592 name:Test
table: 5x5 mode: medium score: 2707 name:Test
如何在file.write
或file.close
之后对每行进行排序?
我希望它只按表排序。只要7x7的所有表格都是7x7的表格,它的顺序并不重要。
我试过这样做:
def save_score(score):
name = input("type a name")
file = open("highscores.txt", "a")
file.write("table: "+str(GRID_TILES)+"x"+str(GRID_TILES)+"\t mode: "+str(Dif) +"\t score: "+str(score)+"\t name: "+str(name)+"\n")
file.close()
file = open("scores.txt", "r")
file2 = open("highscores.txt", "w")
file2.writelines(sorted(file, key=lambda line:str(line.split()[0])))
file.close()
file2.close()
我希望尽可能缩短我的代码,因为整个扫雷都会占用相当多的代码。
答案 0 :(得分:0)
这是一种方式:
import shutil
from tempfile import NamedTemporaryFile
def insert_sorted(file_obj, in_line):
flag = False
with NamedTemporaryFile(delete=False, mode="w+") as temp:
try:
val = int(in_line.split()[-2])
except (IndexError, ValueError):
raise Exception("Invalid format")
for line in file_obj:
try:
lineval = int(line.split()[-2])
except (IndexError, ValueError):
print("""following line has an invalid format,\
and gets escaped\n{}""".format(line))
else:
# Write larger score first when we find smaller score
if lineval <= val:
temp.write(in_line)
temp.write(line)
flag = True
break
else:
temp.write(line)
for line in file_obj:
temp.write(line)
# if the score of the in_line is grater than all the lines write it at the trailing.
if not flag:
temp.write(in_line)
return temp
with open(file_name) as f:
in_line = "table: 10x10 mode: easy score: 8592 name:Test"
temp = insert_sorted(f, in_line)
shutil.move(temp.name, file_name)
答案 1 :(得分:0)
def save_score(score):
name = input("type a name")
with open("scores.txt", "a") as file:
file.write("table: {}x{}\t mode: {}\t score: {}\t name: {}\n".format(
GRID_TILES, GRID_TILES, Dif, score, name))
with open("scores.txt") as file, open("highscores.txt", "w") as file2:
file2.writelines(sorted(file, key=lambda line: line.split()[1]))
感谢Frerich Raabe给我一个答案!