Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何保存和提取外部文件上的分数和数据,并将其排序为高分_Python_File_Comparison - Fatal编程技术网

Python:如何保存和提取外部文件上的分数和数据,并将其排序为高分

Python:如何保存和提取外部文件上的分数和数据,并将其排序为高分,python,file,comparison,Python,File,Comparison,因此,对于我开始学习CS的许多代码来说,我想知道如何保存和读取外部文件上的高分。 我知道如何以基本方式对外部文本文件进行读写,但仅此而已——我不知道如何将其提取为整数或对数据进行排序 请有人帮我告诉我应该使用什么样的外部文件或一些代码来提取/排序数据作为整数? (请注意,这是我的第一篇文章,请原谅我的错误或格式错误) 我需要某种形式的方法来比较分数和文件中的内容,因为文本文件显然不是用来存储和比较整数的 感谢所有答复。谢谢 以下是一个示例: highscores.txt 1,2 5,5 6,2

因此,对于我开始学习CS的许多代码来说,我想知道如何保存和读取外部文件上的高分。 我知道如何以基本方式对外部文本文件进行读写,但仅此而已——我不知道如何将其提取为整数或对数据进行排序

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

我需要某种形式的方法来比较分数和文件中的内容,因为文本文件显然不是用来存储和比较整数的

感谢所有答复。谢谢

以下是一个示例:

highscores.txt

1,2
5,5
6,2
4,3
5,2

你能添加你的文件内容吗?在这个问题上有很大的不同,我们需要知道这些数字是如何分开或对齐的,以便计算机读取。
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()