Python - 使用标题进行文件操作

时间:2013-04-21 10:49:23

标签: python file document file-manipulation

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

2 个答案:

答案 0 :(得分: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']

答案 1 :(得分: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']