[英]how to read previous and next line if the current line is valid for an IF statement in Python
我正在以這種方式讀取壓縮文件
import sys;
import gzip;
import csv;
def iscomment(s): ##function to get rid of the header of the file which every line starts with #
return s.startswith('#')
with gzip.open(sys.argv[1], 'r') as f:
for line in dropwhile(iscomment, f):
for line in csv.reader(f, delimiter="\t"):
if (int(line[1]) in myHdictionary):
print PreviousLine,"\n",line,"\n",NextLine,"\n"
else:
continue
因此,如果當前行符合IF語句,我想檢索文件當前行的上一行和下一行。
任何建議將不勝感激! 提前致謝!
不要試圖向前看何時會倒退:
from collections import deque
from itertools import islice, dropwhile
import csv
def iscomment(row): return row[0][0] == '#'
with gzip.open(sys.argv[1], 'r') as f:
reader = dropwhile(iscomment, csv.reader(f, delimiter="\t"))
history = deque(islice(reader, 2), maxlen=2)
for row in reader:
if history[-1][1] in myHdictionary:
print history[0]
print history[-1]
print row
history.append(row)
您需要將csv.reader()
本身包裝在dropwhile()
迭代器中(條件已調整); 否則,您將跳過csv
閱讀器永遠看不到的開頭。
deque
對象始終保持前兩行,使您在瀏覽CSV文件時可以窺視這些行。 history[-1]
是前一行, history[0]
是前一行。 如果history[-1]
1列在myHdictionary
,則您的條件匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.