处理文件时,如何获取当前行号?

发布于 2024-11-06 02:22:31 字数 250 浏览 2 评论 0原文

当我使用下面的构造循环文件时,我还需要当前行号。

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

是否存在类似的东西?

    for line, lineno in f:

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:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜尕妞 2024-11-13 02:22:31
for lineno, line in enumerate(f, start=1):

如果您遇到的 Python 版本不允许您设置枚举的起始数字(此功能已在 Python 2.6 中添加),并且您想使用此功能,那么最好的解决方案是可能是提供一个实现,而不是调整内置函数返回的索引。这是这样一个实现。

def enumerate(iterable, start=0):
    for item in iterable:
        yield start, item
        start += 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
冬天旳寂寞 2024-11-13 02:22:31

如果您使用的是Python2.6+,kindall的答案涵盖了

Python2.5及更早版本不支持枚举的第二个参数,因此您需要使用类似这样的东西

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

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

除非您同意第一行是数字0

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文