tags:

views:

304

answers:

4

I have a file with data. The file is the output generated from a shell scripting file:

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

How can I get a = 869 from this?

+3  A: 

You can also use csv module with delimiter |.

Eugene Morozov
+9  A: 

You could do this:

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 Eugene 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
Paolo Bergantino
I think it is better to construct a dictionary from the list of pairs. This way it is just one line and is doable with list comprehensions. See http://stackoverflow.com/questions/751557/parse-shell-file-output-with-python/751613#751613
jetxee
Personally I'm not a big fan of golfing every problem. Maybe it's because I'm new with Python but list comprehensions don't scream "beauty" to me like they apparently do to everyone.
Paolo Bergantino
Sure, it is a matter of taste. I find it more clear and local (I don't have to care if dict is empty or not).
jetxee
+4  A: 
lines =  file("test.txt").readlines()
d = dict([[i.strip() for i in l.split("|")[1:3]] for l in lines if l.strip()])

For example:

>>> 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'
jetxee
A: 

Maybe not the most Pythonic way, but this should work if your shell output is stored in f.txt and you are looking for every 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()
PTBNL