python:将特定行从一个文件复制到另一个文件

时间:2015-11-03 12:55:41

标签: 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始终为空。 感谢

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)

正在运作