Python 如何将文件一分为二,然后只搜索下半部分?

Python 如何将文件一分为二,然后只搜索下半部分?,python,parsing,io,Python,Parsing,Io,如何根据关键字将一个文件分成两部分…然后通过该文件解析表达式“chain”edt_2;?下面是一个示例文本文件(名为temp.txt): 如果我们要在查找关键字时拆分文件,然后搜索表达式chain“edt\uu,这是一种方法: # 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]

如何根据关键字将一个文件分成两部分…然后通过该文件解析表达式“chain”edt_2;?

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

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

# 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)

这就是你想做的吗?

我想你在找这个。非常感谢,Robbie.)不过,我确实遇到了一个错误:回溯(上次的最新调用):文件“split_File.py”,第32行,在exLoc=[I.find('chain'edt_')中,用于第二部分中的I]。索引(0)值错误:0不在列表中。错误是说其中没有字符串为'chain'edt'的行。是这样吗?不,我只是在脚本生成的第二个文件中检查并发现了这一点:chain“edt_dispipebpar1_channel1”=“0好的-我现在不在我的计算机旁,但很快会检查并编辑我的答案好的检查新代码(刚刚用exLoc=…)更改了行)
# 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)