python中如何获取当前打开的文件行?
假设你打开一个文件,并在文件中的某处执行seek(),你如何知道当前文件行?
(我个人用一个临时文件类解决了这个问题,该类在扫描文件后将搜索位置映射到行,但我想查看其他提示并将这个问题添加到 stackoverflow,因为我无法在谷歌)
Suppose you open a file, and do an seek() somewhere in the file, how do you know the current file line ?
(I personally solved with an ad-hoc file class that maps the seek position to the line after scanning the file, but I wanted to see other hints and to add this question to stackoverflow, as I was not able to find the problem anywhere on google)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您使用seek()时,python会使用指针偏移量跳转到文件中所需的位置。但为了知道当前的行号,您必须检查该位置之前的每个字符。因此,您不妨放弃seek(),转而使用read():
替换
为
也许您不希望使用f.read(num),因为如果num 非常大,这可能需要大量内存。在这种情况下,您可以使用如下生成器:
这相当于
f.seek(num)
,并具有为您提供line_number
的额外好处。When you use seek(), python gets to use pointer offsets to jump to the desired position in the file. But in order to know the current line number, you have to examine each character up to that position. So you might as well abandon seek() in favor of read():
Replace
with
Perhaps you do not wish to use f.read(num) since this may require a lot of memory if num is very large. In that case, you could use a generator like this:
This is equivalent to
f.seek(num)
with the added benefit of giving youline_number
.以下是我如何使用尽可能多的惰性来解决这个问题:
对于可读性稍差但更惰性的方法,请使用
enumerate
和dropwhile
:Here's how I would approach the problem, using as much laziness as possible:
For a slightly less readable but much more lazy approach, use
enumerate
anddropwhile
: