0

因此,对于我为开始我的 CS 教育而编写的许多代码,我正在研究如何在外部文件上保存和读取高分。我知道如何以基本方式对外部文本文件进行读写操作,但仅此而已 - 我不知道如何将其提取为整数或对数据进行排序。

请有人帮我告诉我应该使用什么外部文件或我可以使用一些代码将数据提取/排序为整数?(注意这是我的第一篇文章,所以请原谅我的失败或格式)

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

我需要某种形式的方法,然后我可以将分数与文件中的内容进行比较,因为文本文件显然不用于存储和比较整数。

所有答复表示赞赏。谢谢!

4

1 回答 1

0

这是一个示例:

高分.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()
于 2020-01-15T22:04:02.690 回答