2017-06-08 147 views

回答

0

如果你的问题是,原来的文件,该文件是startWord和endWord之间的复制部分,您可以使用此这是非常轻微的 Extract subset of file in bash or Python

begin = 'BEGINSTRING' 
end = 'ENDSTRING' 

with open(f, 'r') as input_file: 
    tmp = [] 
    flag = False 

    for line in input_file.readlines(): 

    if begin in line:    
     flag = True 
     index = line.find(begin) 
     tmp.append(line[index:]) 
     continue 
    elif flag: 
     tmp.append(line) 
    elif end in line: 
     index = line.find(end)    
     tmp.append(line[:index+1]) 
     break 
    else: 
     pass 

with open(f + '_new', 'w') as output_file: 
    for line in tmp: 
    output_file.write(line) 
+0

谢谢,Sandeep! =)这工作很好。 –

+0

如果我想添加strip(),开始和结束......我该怎么做?我正在寻找一个确切的短语。 –

+0

@CookiesMonster我并没有完全理解你想使用strip()。 如果您想将它用于开始和结束的单词,您可以在第1行和第2行中使用它,即begin ='BEGINSTRING'.strip()和类似的结束.....。 如果你想从文件的最后一个子集中去掉字符,你可以在for循环之后和写入新文件之前使用tmp.strip()。 – Sandeep