python - 如何在 python 3 中每隔一行写一次?

标签 python

def every_second_line(report):
    """ (Open File for reading) -> list of str

    Return a list containing every second line (with leading and trailing
    whitespace removed) in report, starting with the first line.
    """
    list=[]
    for line in report:
        list.append(line.strip)
    report.readline()
    return list

我在复习考试时偶然发现了这段代码。有人可以告诉我为什么这段代码不起作用吗?提前致谢!

最佳答案

对代码的最小改动只是将 report.readline() 放入 for 循环中。

for line in report:
    lst.append(line.strip())
    report.readline()

您还可以使用 next(report)(适用于所有迭代器,而不仅仅是文件对象)而不是 report.readline()

请注意,如果您的文件有奇数行,report.readline() 可能会抛出 StopIteration 错误(或者是 EOFError?) Best to catch that.

for line in report:
    lst.append(line.strip())
    try:
        next(report)
    except (StopIteration, EOFError): # because I don't remember which it throws
        break # leave the for loop

或者如 JuniorCompressor 在评论中指出的那样,您可以使用 next 的可选参数来完全忽略

for line in report:
    lst.append(line.strip())
    next(report, None)

关于python - 如何在 python 3 中每隔一行写一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29217243/

相关文章:

python - 是否有推荐的方法来调试 Python 中 Web 应用程序后端卡住的原因?

python - 使用 python 对药片进行雕刻印记检测

python - 二进制补码函数输出 -1 的错误结果

python - 暴露或隐藏依赖对象?

python - 谷歌云视觉批量处理大量图像使用python

python - 使用 pyDub 分割长音频文件

python - Django 动态访问相关属性?

python - C相当于Python的struct.pack?

python - 仅绘制大型 Pandas 数据框中的唯一行

Python 使用数据/时间作为 x 轴?