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/