[英]Writing and Reading to/from a file in 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.")
您應該嘗試使用逗號分隔值(CSV)寫入文件。 雖然該術語使用“逗號”一詞,但該格式實際上僅表示任何類型的一致字段分隔符,每個記錄都在一行上。
Python有一個csv模塊,以幫助讀取和編寫此格式。 但是我將忽略它,並出於您的家庭作業目的手動進行。
假設您有一個像這樣的文件:
Bob,100
Jane,500
Jerry,10
Bill,5
James,5000
Sara,250
我在這里使用逗號。
f = open("scores.txt", "r")
scores = []
for line in f:
line = line.strip()
if not line:
continue
name, score = line.strip().split(",")
scores.append((name.strip(), int(score.strip())))
print scores
"""
[('Bob', 100),
('Jane', 500),
('Jerry', 10),
('Bill', 5),
('James', 5000),
('Sara', 250)]
"""
您不必在每次閱讀和添加列表時對列表進行排序。 您可以一次完成一次:
scores.sort(reverse=True, key=lambda item: item[1])
top5 = scores[:5]
我知道lambda
對您來說可能是新手。 這是一個匿名函數。 我們在這里使用它來告訴sort函數在哪里可以找到比較的關鍵字。 在這種情況下,我們是說要對分數列表中的每個項目使用分數字段(索引1)進行比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.