在函数中使用 readline() 来读取日志文件不会迭代

using readline() in a function to read through a log file will not iterate

在下面的代码中 readline() 不会递增。我试过在 readline() 中使用值、无值和变量。当不使用值时,我不会关闭文件以便它会迭代,但是那和其他尝试都没有奏效。

只是第一个字节被反复显示。

如果我不使用函数而只是将代码放在 while 循环中(readline() 中没有 'line' 变量),它会按预期工作。它将遍历日志文件并打印出不同的十六进制数字。

i=0
x=1

def mFinder(line):
    rgps=open('c:/code/gps.log', 'r')
    varr=rgps.readline(line)
    varr=varr[12:14].rstrip()
    rgps.close()
    return varr


while x<900:
    val=mFinder(i)
    i+=1
    x+=1
    print val
    print 'this should change'

看来您误解了 file.readline() 的作用。传入参数不会告诉方法读取特定编号的行。

文档会告诉您发生了什么:

file.readline([size])
Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned.

我的粗体强调,您传递的是最大字节数,rgps.readline(1) 读取单个字节,而不是第一行。

您需要保留对文件对象的引用,直到您使用它为止,并在其上重复调用 readline() 以获得连续的行。您可以将文件对象传递给函数调用:

def finder(fileobj):
    line = fileobj.readline()
    return line[12:14].rstrip()

with open('c:/code/gps.log') as rgps:
    x = 0
    while x < 900:
        section = finder(rgps)
        print section
        # do stuff
        x += 1

您也可以直接循环文件,因为它们是迭代器:

for line in openfilobject:

或使用 next() function to get a next line, as long as you don't mix .readline() calls and iteration (including next()). If you combine this witha generator function,您可以将文件对象完全留给一个单独的函数,该函数将读取行并生成部分,直到您完成:

def read_sections():
    with open('c:/code/gps.log') as rgps:
        for line in rgps:
            yield line[12:14].rstrip()

for section in read_sections():
    # do something with `section`.