classFileLineWrapper(object):def__init__(self,file):self.f =fileself.curr_line =0defclose(self):returnself.f.close()defreadline(self):self.curr_line +=1returnself.f.readline()# to allow using in 'with' statementsdef__enter__(self):returnselfdef__exit__(self, exc_type, exc_val, exc_tb):self.close()
Python
并使用上述代码:
f =FileLineWrapper(open("my_file","r"))
f.readline()print(f.line)
Python
这将输出:1
如果您仅使用readline方法,则还有其他方法可以跟踪行号。例如,
f=open("my_file","r")for line_no, line inenumerate(f):print line_no
f.close()