숙제 할당에 도움을 주시면 감사하겠습니다. 파일을 확인해야하는 클래스에 대한 간단한 프로그램입니다. 파일이 있으면 파일을 읽고로드합니다. 데이터를 프로그램에 추가하여 점수를 나열하고 더 많은 점수를 추가 할 수 있습니다. 그 가정 상위 5 점만 유지.파이썬에서 파일 쓰기 및 읽기
그런 다음 프로그램을 닫을 때 (옵션 0을 선택하면) 상위 5 개 점수를 scores.txt
파일에 작성해야합니다. 제대로 작동 할 수 있다고 생각합니다. 프로그램을 올바르게 읽고 scores
파일을 채우는 데 문제가 있습니다. 당신은 Comma-Separated-Value (CSV)에서 파일을 작성하려고한다
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.")
게시물을 약간 다시 포맷했습니다. 한 번에 한 가지만 편집하십시오. –
감사합니다. 나는 그것을 기억할 것이다. –
다른 줄에있는 각 필드 대신 CSV 형식으로 파일을 작성하면 훨씬 쉽습니다. – jdi