Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When processing a file, how do I obtain the current line number?

When I am looping over a file using the construct below, I also want the current line number.

    with codecs.open(filename, 'rb', 'utf8' ) as f:
        retval = []
        for line in f:
            process(line)

Does something akin to this exist ?

    for line, lineno in f:
like image 311
Frankie Ribery Avatar asked May 10 '11 03:05

Frankie Ribery


People also ask

How do you get the line number in a file in Python?

Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.

How do I get line numbers from a text file in C++?

Use std::getline to read each line in one by one. Keep an integer indicating the number of lines you have read: initialize it to zero and each time you call std::getline and it succeeds, increment it. Save this answer.

How do you get the line number error in Python?

Use sys. exc_info() to retrieve the file, line number, and type of exception. In an exception block, call sys. exc_info() to return a tuple containing the exception type, the exception object, and the exception traceback.


2 Answers

for lineno, line in enumerate(f, start=1):

If you are stuck on a version of Python that doesn't allow you to set the starting number for enumerate (this feature was added in Python 2.6), and you want to use this feature, the best solution is probably to provide an implementation that does, rather than adjusting the index returned by the built-in function. Here is such an implementation.

def enumerate(iterable, start=0):
    for item in iterable:
        yield start, item
        start += 1
like image 72
kindall Avatar answered Oct 13 '22 14:10

kindall


If you are using Python2.6+, kindall's answer covers it

Python2.5 and earlier don't support the second argument to enumertate, so you need to use something like this

for i, line in enumerate(f):
    lineno = i+1

or

for lineno, line in ((i+1,j) for i,j in enumerate(f)):

Unless you are ok with the first line being number 0

like image 26
John La Rooy Avatar answered Oct 13 '22 15:10

John La Rooy