Is there an easy way to tell which line number a file pointer is on?
You might find the fileinput
module useful. It provides a generalized interface for iterating over an arbitrary number of files. Some relevant highlights from the docs:
fileinput.lineno()
Return the cumulative line number of the line that has just been read. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line.
fileinput.filelineno()
Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file.
A typical solution to this problem is to define a new class that wraps an existing instance of a file
, which automatically counts the numbers. Something like this (just off the top of my head, I haven't tested this):
class FileLineWrapper(object):
def __init__(self, f):
self.f = f
self.line = 0
def close(self):
return self.f.close()
def readline(self):
self.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()
Use it like this:
f = FileLineWrapper(open("myfile.txt", "r"))
f.readline()
print(f.line)
It looks like the standard module fileinput
does much the same thing (and some other things as well); you could use that instead if you like.