Python Sorting a text file by fields
class, python, sorting, text-files
Solution
with open("info.txt") as inf:
data = []
for line in inf:
line = line.split()
if len(line)==4:
data.append(line)
data.sort(key=lambda s:(s[2],s[1]))
If you want to get a bit fancier,
from collections import namedtuple
Input = namedtuple('Input', ('name', 'time', 'identity', 'domain'))
with open("info.txt") as inf:
inf.next() # skip header
data = [Input(*(line.split()) for line in inf]
data.sort(key=lambda s:(s['identity'],s['time']))
If you really, really want to use a class, try:
import time
class Data(object):
def __init__(self, event, time_, identity, domain):
self.event = event
self.time = time.strptime(time_, "%H%M")
self.identity = identity
self.domain = domain
with open("info.txt") as inf:
data = []
for line in inf:
try:
data.append(Data(*(line.split()))
except TypeError:
# wrong number of arguments (ie header or footer)
pass
data.sort(key=lambda s:(s.identity,s.time))
Problem
I'm having some trouble sorting data from a text file by a certain field. Possibly by multiple fields later. The .txt is several thousands of lines of code. I'm brand new to python so my code is probably a bit messy. For example, this is the textfile i would read from: ``` stuff 123 1200 id-aaaa stuart@test.com 322 1812 id-wwww machine-switch@test.com 839 1750 id-wwww gary2-da@test.com 500 0545 id-aaaa abc123@test.com 525 1322 id-bbbb zyx321@test.com ``` my code so far is as follows: ``` filelist = open("info.txt").readlines() splitlist = list() class data: def __init__(self, eventName, time, identity, domain): self.evenName = eventName self.time = time self.identity = identity self.domain = domain for line in filelist: filelist = list.split(', ') splitlist.append(filelist) for column in splitlist: if (len(column) > 1): #to skip the first line eventName = column[0].strip() time = column[1].strip() identity = column[2].strip() domain = column[3].strip() ``` I want to sort the .txt file line by line by the identity, then maybe by time. I saw that this could be done by classes in the python tutorial, so i'm trying to go that route. Please advise. Thank you!