我正在尝试创建一个仅包含一个数字的文件;我正在写的游戏的高分。
我有
f = open('hisc.txt', 'r+')
和
f.write(str(topScore))
我想知道该怎么做是:
- 擦除整个文件
- 获取文件中的数字并使其成为游戏中的变量
- 检查topScore是否高于文件中的数字,如果是则替换
擦除整个文件
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))
也许这是我的偏好,但我更习惯于在初始化时使用的习语,你做
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()
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'