[英]In Python, how to test whether a line is the last one?
假設我要處理文件的每一行,但最后一行需要特殊處理:
with open('my_file.txt') as f:
for line in f:
if <line is the last line>:
handle_last_line(line)
else:
handle_line(line)
問題是,如何實施? 在Python中似乎沒有檢測文件結尾的功能。
除了將行讀入列表(使用f.readlines()或類似方法)之外,還有其他解決方案嗎?
處理上一行:
with open('my_file.txt') as f:
line = None
previous = next(f, None)
for line in f:
handle_line(previous)
previous = line
if previous is not None:
handle_last_line(previous)
當循環終止時,您知道剛剛讀取了最后一行。
通用版本允許您分別處理最后N行,請使用collections.deque()
對象 :
from collections import deque
from itertools import islice
with open('my_file.txt') as f:
prev = deque(islice(f, n), n)
for line in f:
handle_line(prev.popleft())
prev.append(line)
for remaining in prev:
handle_last_line(remaining)
您可以使用itertools.tee
來迭代一個可迭代對象的兩個副本:
next_lines, lines = itertools.tee(file_object)
next(next_lines)
for next_line, line in zip(next_lines, lines):
handle_line(line)
last_line = next(lines, None)
if last_line is not None:
handle_last_line(last_line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.