3

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
Will Vousden
  • 32,488
  • 9
  • 84
  • 95
Reece
  • 29
  • 4

3 Answers3

4

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.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
3

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

rohitkulky
  • 1,182
  • 10
  • 24
  • This is a good and easy to implement answer. The OP is new to Python though, so you could perhaps add a small description line-by-line of what your code does? As comments within the code would be great. – Gabriel Jan 13 '16 at 15:12
1

Do as this,

Get File content:

with open(yourfile, "r") as f:
    data = [l.split(" ") for l in f]

sort it:

sortedList = sort(data, key=lambda x: int(x[1]))

or using itemgetter:

import operator
sortedList = sort(data, key=operator.itemgetter(1))
Netwave
  • 40,134
  • 6
  • 50
  • 93