簡體   English   中英

有效讀取文件中的某一行

[英]Efficiently reading a certain line in a file

在 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”這樣的概念嗎(如果是這樣會更快嗎?)

如果您不需要均勻分布(即可以選擇某條線的機會並不對所有線均等)和/或如果您的線長度都大致相同,則選擇隨機線的問題可以簡化為:

  1. 確定文件的大小(以字節為單位)
  2. 尋找隨機位置
  3. 如果有,則搜索最后一個換行符(如果沒有前一行,則可能沒有)
  4. 選取直到下一個換行符或文件末尾的所有文本,以先到者為准。

對於(2),您對需要向后搜索多遠才能找到前一個換行符進行有根據的猜測。 如果您可以判斷一行平均為n個字節,那么您可以一步讀取前n個字節。

幾天前我遇到了這個問題,我使用了這個解決方案。 我的解決方案類似於@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計數器避免被阻塞。 該算法嘗試從最后 512 個字符中獲取最后一行,然后是 1024、2048 ......如果在第th迭代時仍然沒有完整的行,則停止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM