-2

我如何让 python 运行一个 .txt 文档,找到一个特定的标题,然后将每一行的信息放入一个列表中进行打印?然后一旦完成,寻找另一个标题并对那里的信息做同样的事情......

4

2 回答 2

1

文件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']
于 2013-04-21T11:35:55.733 回答
1

如果您有一个 csv 文件,如下所示:

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

然后按照您的要求执行以下操作(如果我理解正确的话)

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

例如:

print(getColumn("h1",'cf.csv') )
>>> ['a', 'd', 'g']
于 2013-04-21T11:11:27.407 回答