python中如何获取当前打开的文件行?

发布于 2024-08-12 21:19:20 字数 135 浏览 9 评论 0原文

假设你打开一个文件,并在文件中的某处执行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 技术交流群。

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

发布评论

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

评论(2

贱贱哒 2024-08-19 21:19:20

当您使用seek()时,python会使用指针偏移量跳转到文件中所需的位置。但为了知道当前的行号,您必须检查该位置之前的每个字符。因此,您不妨放弃seek(),转而使用read():

替换

f = open(filename, "r")
f.seek(55)

f = open(filename, "r")
line=f.read(55).count('\n')+1
print(line)

也许您不希望使用f.read(num),因为如果num 非常大,这可能需要大量内存。在这种情况下,您可以使用如下生成器:

import itertools
import operator
line_number=reduce(operator.add,( f.read(1)=='\n' for _ in itertools.repeat(None,num)))
pos=f.tell()

这相当于 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

f = open(filename, "r")
f.seek(55)

with

f = open(filename, "r")
line=f.read(55).count('\n')+1
print(line)

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:

import itertools
import operator
line_number=reduce(operator.add,( f.read(1)=='\n' for _ in itertools.repeat(None,num)))
pos=f.tell()

This is equivalent to f.seek(num) with the added benefit of giving you line_number.

你与昨日 2024-08-19 21:19:20

以下是我如何使用尽可能多的惰性来解决这个问题:

from random import randint
from itertools import takewhile, islice

file = "/etc/passwd"
f = open(file, "r")

f.seek(randint(10,250))
pos = f.tell()

print "pos=%d" % pos

def countbytes(iterable):
    bytes = 0
    for item in iterable:
        bytes += len(item)
        yield bytes

print 1+len(list(takewhile(lambda x: x <= pos, countbytes(open(file, "r")))))

对于可读性稍差但更惰性的方法,请使用 enumeratedropwhile

from random import randint
from itertools import islice, dropwhile

file = "/etc/passwd"
f = open(file, "r")

f.seek(randint(10,250))
pos = f.tell()

print "pos=%d" % pos

def countbytes(iterable):
    bytes = 0
    for item in iterable:
        bytes += len(item)
        yield bytes

print list(
        islice(
            dropwhile(lambda x: x[1] <= pos, enumerate(countbytes(open(file, "r"))))
            , 1))[0][0]+1

Here's how I would approach the problem, using as much laziness as possible:

from random import randint
from itertools import takewhile, islice

file = "/etc/passwd"
f = open(file, "r")

f.seek(randint(10,250))
pos = f.tell()

print "pos=%d" % pos

def countbytes(iterable):
    bytes = 0
    for item in iterable:
        bytes += len(item)
        yield bytes

print 1+len(list(takewhile(lambda x: x <= pos, countbytes(open(file, "r")))))

For a slightly less readable but much more lazy approach, use enumerate and dropwhile:

from random import randint
from itertools import islice, dropwhile

file = "/etc/passwd"
f = open(file, "r")

f.seek(randint(10,250))
pos = f.tell()

print "pos=%d" % pos

def countbytes(iterable):
    bytes = 0
    for item in iterable:
        bytes += len(item)
        yield bytes

print list(
        islice(
            dropwhile(lambda x: x[1] <= pos, enumerate(countbytes(open(file, "r"))))
            , 1))[0][0]+1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文