2015-09-26 228 views
-3

我是新的Python。我有一个简单的任务,将特定的文本文件行写入另一个文本文件。文本文件的格式是这样将文本文件的特定行写入文本文件 - Python

.A 
some text1 -- skip 
some text2 -- skip 
.B 
.some text3 -- write 
.some text4 -- write 

我需要跳过.A和.B,当我遇到.B开始从一些text3..etc的新文件写入数据之间的数据。

我使用Python 2.7

我想这一点 -

with open("Myfile.txt","r") as myfile: 
    for line in myfile: 
     if line.startswith(".A"): 
      writefile = open("writefile.txt", "a") 
     else: 
      if not (line.startswith(".B")): 
       continue 
      else: 
       writefile.write(line) 

我想在别的块我搞砸了的东西..

+0

您有什么问题? – saulspatz

+0

请分享你到目前为止所尝试过的 – csharpcoder

回答

0

一个简单的方法是这样的:

fname = 'D:/File.txt' 
content = [] 
with open(fname) as f: 
    content = f.readlines() 
wflag= True 
f = open('D:/myfile.txt','w') 
for line in content: 
    if(line=='.A\n'): 
     wflag = False 
    if(line=='.B\n'): 
     wflag= True 
     continue 
    if(wflag): 
     f.write(line) # python will convert \n to os.linesep 
f.close() 

他们使用一些正则表达式来做更多pythonic方法,但正如你所说你是初学者,所以我发布了一个简单的程序员方法。

0

的问题是不完全清楚,但也许你想是这样的,

skip_line = True 
writefile = open("writefile.txt", "a") 
with open("Myfile.txt","r") as myfile: 
    for line in myfile: 
     if line.startswith(".A"): 
      skip_line = True 
     elif line.startswith(".B"): 
      skip_line = False 
     else: 
      pass 
     if skip_line: 
      continue 
     writefile.write(line)