如何将文件分成两部分,然后只搜索下半部分?

时间:2017-04-25 23:38:26

标签: python parsing io

如何根据关键词将文件分成两部分......然后通过该文件解析表达式" edt _'?

1 个答案:

答案 0 :(得分:0)

以下是一个示例文本文件(名为 temp.txt ):

hello 10 20 30
goodbye 20 30 40
keyword 5 6 7
chain "edt_ 0 1 2
rubbish 2 3 4
more 6 7 8
test 1 2 3

如果我们想要在找到关键字时拆分文件,然后搜索表达式链“edt _ ,这是一种方法:

# Read the file
with open('temp.txt','r') as f:
    data = f.readlines()

# Strip out newline char
data = [i.strip('\n') for i in data]

# Look for keyword
kwLoc = [i.find('keyword') for i in data].index(0)

print 'Keyword found on line {0} - splitting file.'.format(kwLoc)

# Split the file
partOne = data[:kwLoc]
partTwo = data[kwLoc:]

# Optionally save each file
with open('temp_1.txt','w') as f:
    for row in partOne:
        f.writelines(row)
        f.write('\n')

with open('temp_2.txt','w') as f:
    for row in partTwo:
        f.writelines(row)
        f.write('\n')

# Now search the file for the expression - returning the row where it occurs

exLoc = [i.find('chain "edt_')>0 for i in partTwo].index(True)


print 'Found expression chain "edt on row {0}.'.format(exLoc)

这是你想做的吗?