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?

1
  • Better title: how to read (or parse) columnar data file in Python? Commented Apr 15, 2009 at 13:18

4 Answers 4

9

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
Sign up to request clarification or add additional context in comments.

3 Comments

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 stackoverflow.com/questions/751557/…
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.
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).
4
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'

Comments

3

You can also use csv module with delimiter |.

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.