簡體   English   中英

Python:如何在外部文件中保存和提取分數和數據並將它們排序為高分

[英]Python: How to save and extract scores and data on an external file and sort them into highscores

因此,對於開始我的 CS 教育的許多代碼片段,我正在研究如何在外部文件中保存和讀取高分。 我知道如何以基本方式寫入和讀取外部文本文件,但僅此而已 - 我不知道如何將其提取為整數或對數據進行排序。

請有人幫我告訴我應該使用什么外部文件或一些我可以用來將數據提取/排序為整數的代碼嗎? (注意這是我的第一篇文章,所以請原諒我的失敗或格式)

score = dice1 + dice2
highscorefile = open('highscores.txt','r')
cont = highscorefile.read()
file.close()

我需要某種形式的方法,然后我可以將分數與文件中的內容進行比較,因為文本文件顯然不是用於存儲和比較整數。

所有答復表示贊賞。 謝謝!

這是一個示例:

高分.txt

1,2
5,5
6,2
4,3
5,2
# we are creating a file handle here inorder to read file.
highscorefile = open('highscores.txt','r') 
# We are reading the file contents using the read function
cont = highscorefile.read() 
# we are splitting the read content line by line and \n represents new lines here
for line in cont.split('\n'):
# we are again splitting the line by commas and address first item for dice1, second time for dice two and converting them to integers and addressing for the sum
  print(" dice1 : ",line.split(',')[0]," dice2 : ",line.split(',')[1]," sum : ",int(line.split(',')[0]) + int(line.split(',')[2])
#After completing this operations we are closing the file.
highscorefile.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM