2013-12-14 82 views
0

我有一个文件,其中包含以下行。在此我想要读取启动了forw的行和行为之前的行之间的行.txt 。使用python脚本将每组提取的行复制到单独的新文件中。如何从文件中提取特定行并将特定行保存到python中的每个新文件中

forw l1tt DeleteULPhCH 0 
forw l1tt activate 1 
forw l1tt DeleteCCB 0 1 0 
forw l1tt DeleteDLPhCH 0 
BCH_CCB63.txt 
DL_BCH_PhCh.txt 
forw l1tt setuecontext 100 
forw l1tt DeleteCCB 65 1 0 
DL_BCH_PhCh.txt 

我的输出应该是这样的:

forw l1tt activate 1 
forw l1tt DeleteULPhCH 0 
forw l1tt activate 1 
forw l1tt DeleteCCB 0 1 0 
forw l1tt DeleteDLPhCH 0 

在一个文件中。

和在另一文件中它应该是这样的:

forw l1tt setuecontext 100 
forw l1tt DeleteCCB 65 1 0 

我用下面的Python代码:它仅提取第一组output.But的我不能能够提取第二组输出的给定的后打破condition.Please任何人都可以尽快帮助我。

fin=open("script.txt","r") 
fout=open("output.txt","w") 
lines=fin.readlines() 
    for line in lines: 
     if re.search(r"(.*)(.txt)",line): 
      break 
     print line 
    fout.write(line) 
fin.close() 
fout.close() 

回答

0

看来,他不希望包括“.TXT”行到创建的文件

import re 
n = 1 

with open("script.txt","r") as my_file: 
    my_list = [] 
    for line in my_file.readlines(): 
    if not re.search(r"(.*)(.txt)",line): 
     my_list.append(line) 
     with open("output"+str(n)+".txt","w") as out_file: 
     for item in my_list: 
      out_file.write(item) 
    else: 
     if my_list: 
     my_list=[] 
     n += 1 

创建文件:

$ cat output1.txt 
forw l1tt DeleteULPhCH 0 
forw l1tt activate 1 
forw l1tt DeleteCCB 0 1 0 
forw l1tt DeleteDLPhCH 0 

$ cat output2.txt 
forw l1tt setuecontext 100 
forw l1tt DeleteCCB 65 1 0 
+0

非常感谢。他绝对工作100% – user3082400

+0

欢迎您。我很高兴能够提供帮助 – skamsie

0

使用简单幼稚状态机,你可以做这样的:

#!/usr/bin/env python 


n = 0 
output = [] 
state = 0 # 0 = start, 1 = forw 

with open("foo.txt", "r") as f: 
    for line in f: 
     line = line.strip() 
     if "forw" in line: 
      state = 1 
     if state == 1: 
      output.append(line) 
      if ".txt" in line: 
       state = 0 
       with open("{0:d}.txt".format(n), "w") as outf: 
        outf.write("\n".join(output)) 
        outf.write(line) 
       n += 1 
       output = [] 

将会产生以下输出文件:

$ cat 0.txt 
forw l1tt DeleteULPhCH 0 
forw l1tt activate 1 
forw l1tt DeleteCCB 0 1 0 
forw l1tt DeleteDLPhCH 0 
BCH_CCB63.txtBCH_CCB63.txt 

$ cat 1.txt 
forw l1tt setuecontext 100 
forw l1tt DeleteCCB 65 1 0 
DL_BCH_PhCh.txtDL_BCH_PhCh.txt 

这不是很确切你以后,但它很接近。 希望你可以修改这个以适应你的需求。

状态机非常有用!

+0

谢谢你这么much.but我不开放的理解(“{0:d} .txt”.format(n),“w”)作为outf:这一行.....你没有提到“d”range.if {0:d} .txt then文件名将如何来? – user3082400

+0

从上面的示例输出中可以明显看出。输出文件名将是“0.txt”,“1.txt”,“2.txt”,...“N.txt”。 –

相关问题