如何在Python中正确读取大文本文件,以免堵塞内存?

问题描述 投票:0回答:1

所以今天在购买BTC的时候,我搞砸了并且丢失了我的解密密码短语到ATM在电子邮件上自动发送的钱包。

我记得密码短语的最后4个字符,所以我生成了一个单词列表,并想尝试强行进入它。这是一个4MB的文件,脚本检查了所有的可能性,没有运气。然后我意识到这些字母可能是错的,但我仍记得那些4个字符中的数字。突然间,我有2GB文件,由Ubuntu获得SIGKILLed。

这是整个代码,它很短。

#!/usr/bin/python

from zipfile import ZipFile
import sys
i = 0
found = False

with ZipFile("/home/kuskus/Desktop/wallet.zip") as zf:
    with open('/home/kuskus/Desktop/wl.txt') as wordlist:
        for line in wordlist.readlines():
            if(not found):
                try:
                    zf.extractall(pwd = str.encode(line))
                    print("password found: %s" % line)
                    found = True
                except:
                    print(i)
                    i += 1
            else: sys.exit()

我认为问题是文本文件填满了内存,因此操作系统会杀死它。我真的不知道我怎么能读取文件,可能是1000行,然后清理它再做1000行。如果有人可以帮助我,我将非常感激,提前谢谢你:)哦,文本文件有大约300万行,如果它的重要。

python file large-files
1个回答
3
投票

通常,最好的办法是直接迭代文件。文件处理程序将充当生成器,一次生成一行,而不是将它们全部聚合到内存中一次到列表中(如fh.readlines()所做):

with open("somefile") as fh:
     for line in fh:
         # do something

此外,如果您选择,文件句柄允许您读取特定数量的数据:

with open("somefile") as fh:
    number_of_chars = fh.read(15) # 15 is the number of characters in a StringIO style handler
    while number_of_chars:
        # do something with number_of_chars
        number_of_chars = fh.read(15)

或者,如果您想要读取特定行数:

with open('somefile') as fh:
    chunk_of_lines = [fh.readline() for i in range(5)] # this will read 5 lines at a time
    while chunk_of_lines:
        # do something else here
        chunk_of_lines = [fh.readline() for i in range(5)]

其中fh.readline()类似于在for循环中调用next(fh)

在后两个例子中使用while循环的原因是因为一旦文件完全迭代,fh.readline()fh.read(some_integer)将产生一个空字符串,它充当False并将终止循环

© www.soinside.com 2019 - 2024. All rights reserved.