How to get the current open file line in Python?

PythonServer Side ProgrammingProgramming

Python doesn't support this directly. You could write a wrapper class for it. 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 as:

f = FileLineWrapper(open("my_file", "r"))
f.readline()
print(f.line)

This will give the output: 1

There are other methods to keep 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()
raja
Published on 22-Dec-2017 11:51:00
Advertisements