Python command line output

I have a data file. A file is the result generated from a shell script file:

|a |869 | |b |835 | |c |0 | |d |0 | |e |34 | |f |3337 

How can I get a = 869 from this?

+4
source share
4 answers

You can do it:

 output = {} for line in open("myfile"): parts = line.split('|') output[parts[1].strip()] = parts[2].strip() print output['a'] // prints 869 print output['f'] // prints 3337 

Or, using the csv module, as suggested by Evgeny Morozov:

 import csv output = {} reader = csv.reader(open("C:/output.txt"), delimiter='|') for line in reader: output[line[1].strip()] = line[2].strip() print output['a'] // prints 869 print output['f'] // prints 3337 
+9
source
 lines = file("test.txt").readlines() d = dict([[i.strip() for i in l.split("|")[1:3]] for l in lines if l.strip()]) 

For instance:

 >>> lines = file("test.txt").readlines() >>> d = dict([[i.strip() for i in l.split("|")[1:3]] for l in lines if l.strip()]) >>> d['a'] '869' 
+4
source

You can also use csv module with delimiter | .

+3
source

Maybe not the most Pythonic way, but this should work if your shell output is stored in the f.txt file and you are looking for each line to be processed:

 h = open("f.txt", "rt") inp = h.readline() while inp: flds = inp.split('|') str = flds[1].strip() + " = " + flds[2].strip() print str inp = h.readline() 
0
source

All Articles