处理文件时,如何获取当前行号?
当我使用下面的构造循环文件时,我还需要当前行号。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您遇到的 Python 版本不允许您设置枚举的起始数字(此功能已在 Python 2.6 中添加),并且您想使用此功能,那么最好的解决方案是可能是提供一个实现,而不是调整内置函数返回的索引。这是这样一个实现。
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.如果您使用的是Python2.6+,kindall的答案涵盖了
Python2.5及更早版本不支持枚举的第二个参数,因此您需要使用类似这样的东西
或
除非您同意第一行是数字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
or
Unless you are ok with the first line being number 0