python读取和写入文件_在python中写入和读取文件

如果你能帮我完成家庭作业,我会很感激的-这是一个简单的班级程序,它应该检查一个文件,如果它存在,它会读取文件,并将数据加载到程序中,这样你就可以列出分数,并添加更多的分数。它应该只保留前5名。在

然后当你关闭程序时(通过选择选项0),它应该将前5个分数写入scores.txt文件。我想我已经让它正常工作了,只是在让程序正确地读取和填充scores文件时遇到了问题。在

以下是我目前为止的代码:scores = []

#Check to see if the file exists

try:

file = open("scores.txt")

for i in range(0, 5):

name = file.readline()

score = file.readline()

entry = (score, name)

scores.append(entry)

scores.sort()

scores.reverse()

scores = scores[:5]

file.close()

except IOError:

print "Sorry could not open file, please check path."

choice = None

while choice != "0":

print """

High Scores 2.0

0 - Quit

1 - List Scores

2 - Add a Score

"""

choice = raw_input("Choice: ")

print ""

# exit

if choice == "0":

print "Good-bye."

file = open("scores.txt", "w+")

#I kinda sorta get this now... kinda...

for entry in scores:

score, name = entry

file.write(name)

file.write('\n')

file.write(str(score))

file.write('\n')

file.close()

# display high-score table

elif choice == "1":

print "High Scores\n"

print "NAME\tSCORE"

for entry in scores:

score, name = entry

print name, "\t", score

# add a score

elif choice == "2":

name = raw_input("What is the player's name?: ")

score = int(raw_input("What score did the player get?: "))

entry = (score, name)

scores.append(entry)

scores.sort()

scores.reverse()

scores = scores[:5] # keep only top 5 scores

# some unknown choice

else:

print "Sorry, but", choice, "isn't a valid choice."

raw_input("\n\nPress the enter key to exit.")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值