将最高分写入数据文件

时间:2013-09-19 20:51:05

标签: python file logging

我正在尝试创建一个只包含一个数字的文件;我正在写的游戏的高分。

我有

f = open('hisc.txt', 'r+')

f.write(str(topScore))

我想知道怎么做:

  • 删除整个文件
  • 获取文件中的数字并将其变为游戏中的变量
  • 检查topScore是否高于文件中的数字,如果是,请将其替换为

3 个答案:

答案 0 :(得分:1)

也许这是我的偏好,但我更习惯于在初始化时使用的习语

f = open('hisc.txt','r')
# do some exception handling so if the file is empty, hiScore is 0 unless you wanted to start with a default higher than 0
hiScore = int(f.read())
f.close()

然后在比赛结束时:

if myScore > hiScore:
   f = open('hisc.txt', 'w')
   f.write(str(myScore))
   f.close()

答案 1 :(得分:1)

  

删除整个文件

with open('hisc.txt', 'w'):
    pass
  

获取文件中的数字并将其变为游戏中的变量

with open('hisc.txt', 'r') as f:
    highScore = int(f.readline())
  

检查topScore是否高于文件中的数字

if myScore > highScore:
  

如果是,请将其替换为

if myScore > highScore:
    with open('hisc.txt', 'w') as f:
        f.write(str(myScore))

全部放在一起:

# UNTESTED
def UpdateScoreFile(myScore):
    '''Write myScore in the record books, but only if I've earned it'''
    with open('hisc.txt', 'r') as f:
        highScore = int(f.readline())
    # RACE CONDITION! What if somebody else, with a higher score than ours
    # runs UpdateScoreFile() right now?
    if myScore > highScore:
        with open('hisc.txt', 'w') as f:
            f.write(str(myScore)) 

答案 2 :(得分:0)

f = open('hisc.txt', 'w')
f.write('10') # first score
f.close()


highscore = 25 #new highscore

# Open to read and try to parse
f = open('hisc.txt', 'r+')
try:
    high = int(f.read())
except:
    high = 0

# do the check
if highscore > high:
    high = highscore

f.close()

# open to erase and write again
f = open('hisc.txt', 'w')
f.write(str(high))
f.close()

# test
print open('hisc.txt').read()
# prints '25'