2015-11-03 70 views
0

我有一个文件,我想从它复制只有特定的行到另一个文件。我试图创建一个功能:python:从一个文件复制特定的行到另一个文件

def copytotemp(logfile, fromline, toline): 
    with open(logfile) as origfile: 
     with open("templog.log", "w") as tempfile: 
      for num, line in enumerate(origfile, 0): 
       if (num + 1) <= fromline and (num + 1) >= toline: 
        tempfile.write(line) 

但tempfile.log总是空空的。 谢谢

+0

'如果(NUM + 1)<= fromline和(NUM + 1)> = toline:'?你确定 ?看起来你有比较运算符向后... –

+0

哦,是的顺便说一声:'enumerate()'采用可选的'start'参数(默认为'0'),所以如果你想要基于1的行号,你可以使用'enumerate (origfile,1)'并摆脱'num + 1'的东西。 –

+0

谢谢,这是问题:) –

回答

0

我有一个操作员的错误。

def copytotemp(logfile, fromline, toline): 
    with open(logfile) as origfile: 
     with open("templog.log", "w") as tempfile: 
      for num, line in enumerate(origfile, 1): 
       if num >= fromline and num <= toline: 
        tempfile.write(line) 

正在

+0

你可能还想看看'itertools.islice()' –

相关问题