-2

How would I get python to run through a .txt document, find a specific heading and then put information from each line in to a list for printing? And then once finished, look for another heading and do the same with the information there...

Manuel Allenspach
  • 12,467
  • 14
  • 54
  • 76
Ashley Collinge
  • 15
  • 1
  • 3
  • 6

2 Answers2

1

If you had a csv file as follows:

h1,h2,h3
a,b,c
d,e,f
g,h,i

Then the following would do as you request (if I understood you correctly)

def getColumn(title,file):
    result = []
    with open(file) as f:
        headers = f.readline().split(',')
        index = headers.index(title)
        for l in f.readlines():
            result.append(l.rstrip().split(',')[index])
    return result

For example:

print(getColumn("h1",'cf.csv') )
>>> ['a', 'd', 'g']
HennyH
  • 7,794
  • 2
  • 29
  • 39
  • Would you like me to explain in detail how it works? Also a simpler and more efficient version could be made by getting substrings based on the comma numbers of the header. – HennyH Apr 21 '13 at 23:34
1

File test.txt

a
b
c
heading1
d
e
f
heading2
g
h
heading3

>>> from itertools import takewhile, imap
>>> with open('test.txt') as f:
        for heading in ('heading1', 'heading2', 'heading3'):
            items = list(takewhile(heading.__ne__, imap(str.rstrip, f)))
            print items


['a', 'b', 'c']
['d', 'e', 'f']
['g', 'h']
jamylak
  • 128,818
  • 30
  • 231
  • 230