+

How do I get the current line of an open file in Python?

Python does not directly support this. You can write a wrapper class to get the current line of an open file. For example,

 class FileLineWrapper (object): def __init __ (self, file): self.f = file self.curr_line = 0 def close (self): return self.f.close () def readline (self): self.curr_line + = 1 return self.f.readline () # to allow using in `with` statements def __enter __ (self): return self def __exit __ (self, exc_type , exc_val, exc_tb): self.close () 

And use the above code like:



< / p>
 f = FileLineWrapper (open ("my_file", "r")) f.readline () print (f.line) 

This will give output: 1



There are other methods for keeping track of the line number if you are only using the readline method. For example,

 f = open ("my_file", "r") for line_no, line in enumerate (f): print line_no f.close () 



Get Solution for free from DataCamp guru