【发布时间】:2013-12-08 23:25:12
【问题描述】:
我正在以这种方式读取压缩文件
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语句,我想检索文件当前行的上一行和下一行。
任何建议将不胜感激! 提前致谢!
【问题讨论】:
-
总是读 3 行,如果中间的行通过了测试,你已经有了另外两行,如果没有,读下一行。
-
你需要在
csv.reader()周围加上dropwhile();您正在做的事情发生可以工作,但是您跳过了太多行。在这种情况下,您必须跳过第一列以#开头的 rows。 -
为了有上一行和下一行:在内存中始终保留 两行。然后,每当这两个匹配中的最后一个匹配时,您就可以打印前两行中的第一行和当前行。
标签: python csv if-statement input