1

Python でファイルを読み取るためのいくつかの異なる方法に出くわしました。どの方法が最も速いのか疑問に思っていました。

たとえば、ファイルの最後の行を読み取るには、次のことができます

input_file = open('mytext.txt', 'r')
lastLine = ""
  for line in input_file:
    lastLine = line

print lastLine # This is the last line

または

fileHandle = open('mytext.txt', 'r')
lineList = fileHandle.readlines()
print lineList[-1] #This is the last line

その特定のケースでは、これは効率の議論にあまり関係がないかもしれないと思います...

質問:

1.ランダムな線を選択するためのより速い方法はどれですか

2. Python で "SEEK" のような概念を扱うことはできますか (そうであれば、より高速ですか?)

4

2 に答える 2

0

数日前にこの問題があり、このソリューションを使用しています。私の解決策は@Frerich Raabeの解決策に似ていますが、ランダムではなく、ロジックだけです:)

def get_last_line(f):
    """ f is a file object in read mode, I just extract the algorithm from a bigger function """
    tries = 0
    offs = -512

    while tries < 5:
        # Put the cursor at n*512nth character before the end.
        # If we reach the max fsize, it puts the cursor at the beginning (fsize * -1 means move the cursor of -fsize from the end)
        f.seek(max(fsize * -1, offs), 2)
        lines = f.readlines()
        if len(lines) > 1:   # If there's more than 1 lines found, then we have the last complete line
            return lines[-1]  # Returns the last complete line
        offs *= 2
        tries += 1

    raise ValueError("No end line found, after 5 tries (Your file may has only 1 line or the last line is longer than %s characters)" % offs)

triesファイルに 1 行 (非常に長い最後の行) がある場合、カウンターはブロックされないようにします。アルゴリズムは、最後の 512 文字から最後の行を取得しようとし、次に 1024、2048 を取得しようとします...そしてth反復時にまだ完全な行がない場合は停止します。

于 2013-08-26T11:14:28.547 に答える