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...
Asked
Active
Viewed 82 times
-2
-
1You need to be more specific, show an example file and some code you have so far – jamylak Apr 21 '13 at 10:50
2 Answers
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