【问题标题】:How to get the current open file line in python?如何在python中获取当前打开的文件行?
【发布时间】:2009-11-27 14:58:20
【问题描述】:

假设你打开一个文件,在文件某处执行 seek(),你怎么知道当前文件行?

(我个人解决了一个临时文件类,该类在扫描文件后将查找位置映射到行,但我想查看其他提示并将此问题添加到 stackoverflow,因为我无法找到谷歌任何地方的问题)

【问题讨论】:

  • 我实际上在某处发布了课程...不知道在哪里。
  • 如果您正在寻找字节偏移量,如果不计算在该位置之前遇到的 \n 个字符的数量,就无法知道第 # 行。至于文件最有效的方法是什么,我不确定....祝你好运!
  • 是的。也许有一些图书馆提供这项服务。正如我所说,我自己实现了它,但如果可能的话,我更愿意将此任务委托给外部库。
  • @Stefano - 你在找stackoverflow.com/questions/1657299/…吗?

标签: python file seek line-count


【解决方案1】:

当你使用 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

【讨论】:

    【解决方案2】:

    以下是我解决问题的方法,尽可能使用懒惰:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      相关资源
      最近更新 更多