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
You can first load your data into pairs like this:
pairs = [l.strip().split(' ') for l in open('data.txt', 'r')]
Now you can sort them like this:
pairs.sort(key = lambda name_score: int(name_score[1]))
Finally, you can change them back into a string like this:
'\n'.join(name_score[0] + ' ' + name_score[1] for name_score in pairs)
You can just open a file, and write this string into it.
You should give pandas a try.
You won't have pandas installed readily with your python. So first you might have to install it - pip install pandas or easy_install pandas - for which you will require python-setuptools. Install them with sudo apt-get install python-setuptools.
import pandas
# Read your file as a dataframe in Pandas.
# "sep" is your delimiter "header" row index are options
myData = pandas.read_csv("/path/to/file.txt",sep=",",header=0)
# Now sort with your column key
sortData = myData.sort(['score'])
# Write out your dataframe to csv
sortData.to_csv("/path/to/output.txt",sep=",",index=False,header=True)
I haven tried it on this data - in some file file.txt
name,score
Reece,10
John,4
Alex,7
Alex,8
John,4
Alex,6
Reece,9
Output -
name,score
John,4
John,4
Alex,6
Alex,7
Alex,8
Reece,9
Reece,10
Edit: header index changed to 0 instead of 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With