Search code examples
pythonfilecomparison

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


So for many pieces of code I've looked at making for beginning my CS education is figuring out how to save and read high scores on an external file. I know how to write and read on an external text file in a basic way but that's it - I don't know how to extract it as an integer or sort the data.

Please can someone help me in telling me what external file i should use or some code i can use to extract/sort data as an integer? (Note this is my first post so please forgive my failure or formatting)

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

I need some form of way that i can then compare score to the contents in the file because text files obviously aren't for storing and comparing integers.

All replies appreciated. Thanks!


Solution

  • Here is a sample:

    highscores.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()