2009-11-27 73 views
7

假设您打开一个文件并在文件的某个地方执行seek(),您如何知道当前的文件行?我亲自解决了一个特殊的文件类,扫描文件后,将查找位置映射到行,但我想看到其他提示,并将此问题添加到stackoverflow,因为我无法找到上的任何地方谷歌)如何在python中获取当前打开的文件行?

+0

我实际上在这里发布了这个类,因此...不知道在哪里。 – 2009-11-27 14:59:06

+1

如果你正在寻找一个字节偏移量,没有办法知道第#行而不计算在该位置之前遇到的#字符数。至于什么是最有效的方式与文件,我不知道....祝你好运! – gahooa 2009-11-27 15:02:23

+0

是的。也许有一些图书馆提供这项服务。正如我所说,我自己实现了它,但如果可能的话,我宁愿将此任务委托给外部库。 – 2009-11-27 15:05:24

回答

4

这里的问题是我会怎么处理这个问题,用尽可能多的懒惰地:

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 
+0

酷酷的使用itertools ... :) – 2009-11-27 15:40:02

6

当您使用seek()时,python会使用指针偏移量跳转到文件中的所需位置。但为了知道当前的行号,你必须检查每个角色到那个位置。所以,你不妨放弃有利于阅读()的征求():

更换

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的好处。

相关问题