如何在Python中下载大文件而不会出现MemoryError?

2024-05-26 16:27:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想以编程方式下载一些文件,但是对于较大的文件,我遇到了MemoryError异常。例如,当我试图下载small file时,代码没问题,但当我试图下载larger file时,我捕获了一个MemoryError。在

这是我的代码:

def __download_gpl_file(accession):
    try:
        bin_string = __get_response(accession)
        if bin_string is None:
            return False
        string = __unzip(bin_string)
    except MemoryError:
        print 'Out of memory for: ' + accession
        return False

    if string:
        filename = DOWNLOADED + accession + '.txt'
        with open(filename, 'w+') as f:
            f.write(string)
        return True
    return False


def __get_response(attempts=5):
    url = __construct_gpl_url(accession)  # Not shown
    response = None
    while attempts > 0:
        try:
            response = urllib2.urlopen(url)
            if response and response.getcode() < 201:
                break
            else:
                attempts -= 1
        except urllib2.URLError:
            print 'URLError with: ' + url
    return response.read()


def __unzip(bin_string):
    f = StringIO(bin_string)
    decompressed = gzip.GzipFile(fileobj=f)
    return decompressed.read()

我能做些什么来下载更大的文件吗?提前谢谢。在


Tags: 文件代码falseurlstringreturnifbin
2条回答

我没有足够的观点来评论黑客狂人的回答,所以我的回答只是他的第一个例子,但有一点修正。在

file = urllib2.urlopen('url') 
with open('filename','w') as f:
    for x in file:
        f.write(x)

我想他是偶然写的。在

不是一次写入整个文件,而是逐行写入:

file = urllib2.urlopen('url')
with open('filename','w') as f:
    for x in file:
        f.write(x)

如果您想加快速度:

^{pr2}$

相关问题 更多 >

    热门问题