您的问题的一个自我解释的解决方案:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# name,score_1,score_2,score_3
# append score to a user
# |_ if user not exists: add user and new score
# |_ an user can't have more than 3 scores
SCORE_FILENAME = "highscores.txt"
MAX_SCORES = 3
def getName():
return raw_input("Please enter the name you wish to add: ").strip()
def getScore():
return raw_input("Please enter the high score: ").strip()
def log(*msg):
print "\t[LOG] " + " ".join([word for word in msg])
if __name__ == "__main__":
# Get new name and Score:
newName = getName()
newScore = getScore()
log("NewUser and NewScore = %s,%s" % (newName,newScore))
# open file and get actual scores:
log("Opening score file: %s" % SCORE_FILENAME)
try: scoresFile = open(SCORE_FILENAME, "r+")
except IOError: scoresFile = open(SCORE_FILENAME, "w+") # File not exists
actualScoresTable = []
for line in scoresFile:
tmp = line.strip().replace("\n","").split(",")
actualScoresTable.append({
"name": tmp[0],
"scores": tmp[1:],
})
scoresFile.close()
log("Actual score table: %s" % actualScoresTable)
# update scores or insert new record:
new = True
for index, record in enumerate( actualScoresTable ):
if record["name"] == newName:
# The user exists in scores table, check how many scores he has:
if len(record["scores"]) >= MAX_SCORES:
# Max. Scores permitted. What to do here?
log("Actual user '%s' already have %s scores '%s'. What we have to do now?" % (newName, MAX_SCORES, ",".join(record["scores"])))
else:
log("Add score '%s' to '%s' that now have [%s]" % (newScore,newName,",".join(record["scores"])))
actualScoresTable[index]["scores"].append(newScore)
new = False
break
if new:
log("User '%s' not exists in actual Scores Table. So append it." % newName)
actualScoresTable.append({
"name": newName,
"scores": [newScore],
})
# Save result to file and close it:
scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
for record in actualScoresTable:
scoresFile.write( "%s,%s\n" % (record["name"], ",".join(record["scores"])) )
log("Writing changes to file: %s" % actualScoresTable)
scoresFile.close()
注意事项:
- 有许多不同的更改来改进此解决方案(使用
with 在打开的文件中操作,如果是记录更新则直接写入 - 不是截断文件,...)。由于您的昵称,我想以这种方式更清楚:“learningpython”;)
- 如果用户已经有了三个分数,我不知道你想做什么(重新开始,从第一个添加的删除,从最后添加的删除(...),所以我没有编码..
编辑以适应新要求:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# name,score_1,score_2,score_3
# append score to a user
# |_ if user not exists: add user and new score
# |_ an user can't have more than 3 scores
SCORE_FILENAME = "highscores.txt"
MAX_SCORES = 3
def getName():
return raw_input("Please enter the name you wish to add: ").strip()
def getScore():
return raw_input("Please enter the high score: ").strip()
def log(*msg):
print "\t[LOG] " + " ".join([word for word in msg])
if __name__ == "__main__":
# Get new name and Score:
newName = getName()
newScore = getScore()
log("NewUser and NewScore = %s,%s" % (newName,newScore))
# open file and get actual scores:
log("Opening score file: %s" % SCORE_FILENAME)
try: scoresFile = open(SCORE_FILENAME, "r+")
except IOError: scoresFile = open(SCORE_FILENAME, "w+") # File not exists
actualScoresTable = []
for line in scoresFile:
tmp = line.strip().replace("\n","").split(",")
actualScoresTable.append({
"name": tmp[0],
"scores": tmp[1:],
})
scoresFile.close()
log("Actual score table: %s" % actualScoresTable)
# update scores or insert new record:
new = True
for index, record in enumerate( actualScoresTable ):
if record["name"] == newName:
# The user exists in scores table, append new score:
log("User '%s' exists in actual Scores Table. So append score '%s' to him." % (newName,newScore))
actualScoresTable[index]["scores"].append(newScore)
# if now we have more than 3 scores, we delete the first one (the oldest one):
if len(record["scores"]) > MAX_SCORES:
log("User '%s' reached max. scores record history, so append score '%s' to him, and delete the oldest: '%s'" % (newName,newScore,actualScoresTable[index]["scores"][0]))
actualScoresTable[index]["scores"].pop(0) # OR del actualScoresTable[index]["scores"][0]
new = False
break
if new:
log("User '%s' not exists in actual Scores Table. So append it." % newName)
actualScoresTable.append({
"name": newName,
"scores": [newScore],
})
# Save result to file and close it:
scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
for record in actualScoresTable:
scoresFile.write( "%s,%s\n" % (record["name"], ",".join(record["scores"])) )
log("Writing changes to file: %s" % actualScoresTable)
scoresFile.close()