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

2024-05-20 19:36:10 发布

您现在位置: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)

但是临时文件.log总是空的。 谢谢


Tags: 文件函数logdefaswithlineopen
1条回答
网友
1楼 · 发布于 2024-05-20 19:36:10

我和接线员出了点差错。在

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)

正在工作

相关问题 更多 >