Sort lines after a readfile?

0

I have a file with several lines such that:

"PseudorangeRateUncertaintyMetersPerSecond",4.2033262571598,"DriftUncertaintyNanosPerSecond","","AccumulatedDeltaRangeState",4,"ReceivedSvTimeNanos",491720918491560.0,"TimeUncertaintyNanos","","SnrInDb","","FullBiasNanos",-1.2125108815424e+18,"State",47,"MultipathIndicator","0","AgcDb","","PseudorangeRateMetersPerSecond",-4.0109888367723,"TimeNanos",39458000000,"Svid",7,"AccumulatedDeltaRangeUncertaintyMeters",3.4028234663853e+38,"AccumulatedDeltaRangeMeters",-136.14045066658,"BiasUncertaintyNanos",5.4542302099749,"BiasNanos",0,"CarrierPhaseUncertainty","","CarrierFrequencyHz2","TimeOffsetNanos",0,"DriftNanosPerSecond","","CarrierFrequencyHz","","ConstellationType","1","CarrierCycles","","ReceivedSvTimeUncertaintyNanos",89,"CarrierPhase","","LeapSecond","","HardwareClockDiscontinuityCount",0,"ElapsedRealtimeMillis",14067926,"Id","Raw","Cn0DbHz",17.306573867798

I have created a program that reads each line and separates it by commas. I need to order the file lines according to the last value of each line.

lectura=[]
while True:
linea=f.readline()
if not linea:break

lect_linea=linea.split(',')
lectura.append(lect_linea)

The problem that I find is that instead of each lect_linea being saved as an object and having as many lines as there is a single value appears in the list with all lect_linea together.

I have asked a couple of times and I have not obtained anything that works, please help

    
asked by Xabier Mikel 07.07.2018 в 04:18
source

1 answer

0

You already have a "list of lists" in variable lectura . What you want now is to order by the last element of each of those lines. For this, sorted() is used, passing it a function to access the last element:

lectura_ordenada = sorted(lectura, key=lambda x: x[-1])

I do not know what the purpose of this sorting will be, if you want to then save it again in a file or if you want to create "objects" of some kind.

Suppose we want to read the lines of a file, sort them by the last value, and store them again in another file. It can be done in a direct way like this:

def ultimo(linea):
    return linea.split(",")[-1]

with open("entrada.txt") as f_in, open("salida.txt","w") as f_out:
    f_out.writelines(sorted(f_in.readlines(), key=ultimo))
    
answered by 07.07.2018 в 09:23