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

谁都会走 提交于 2019-12-08 15:58:17

问题


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:

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/5944908/when-processing-a-file-how-do-i-obtain-the-current-line-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!