At the moment I am trying to sort a file with data such as:
[Name] [Score]
[Name] [Score]
And this goes on. I am trying to sort it by score. So my method is to get all the data from a file and sort it. However I use the sort function and it puts all the data in this format:
[Name] [Score] [Name] [Score]
I want it to be:
[Name] [Score]
[Name] [Score]
then write that to file instead
def fileWrite(fName, fClass):
fileName = "%s %s" %(fClass, ".txt")
fileName = fileName.replace(" ", "")
return(fileName)
def fileSort(fName, fClass):
fSort = open(fName, "a+")
contents = []
i = getFileData(fName)
for getData in range(i):
data1 = fSort.readline()
replaceWith = "%s %s" %(fClass, ";")
data1 = data1.replace(fClass, replaceWith)
contents.append(data1)
contents.sort()
print contents
fSort.truncate(0)
fSort.write(contents)
def getFileData(fName):
i = 0
with open(fName) as f:
for i, l in enumerate(f):
pass
return i + 1
Here is some of the data from the file I need to sort:
Reece 10
John 4
Alex 7
Alex 8
John 4
Alex 6
Reece 9