Python中文
首页
教程
问答
标签
搜索
登录
注册
如何在Python中下载大文件而不会出现MemoryError?
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我想以编程方式下载一些文件,但是对于较大的文件,我遇到了<code>MemoryError</code>异常。例如,当我试图下载<a href="ftp://ftp.ncbi.nlm.nih.gov/geo/platforms/GPL5nnn/GPL5162/soft/" rel="nofollow">small file</a>时,代码没问题,但当我试图下载<a href="ftp://ftp.ncbi.nlm.nih.gov/geo/platforms/GPL5nnn/GPL5293/soft/" rel="nofollow">larger file</a>时,我捕获了一个<code>MemoryError</code>。在</p> <p>这是我的代码:</p> <pre><code>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() </code></pre> <p>我能做些什么来下载更大的文件吗?提前谢谢。在</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>我没有足够的观点来评论黑客狂人的回答,所以我的回答只是他的第一个例子,但有一点修正。在</p> <pre><code>file = urllib2.urlopen('url') with open('filename','w') as f: for x in file: f.write(x) </code></pre> <p>我想他是偶然写的。在</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何找到类似于How'matplotlib.pyplot.gcf()`works?
9 回答
如何找到类字段的定义?
9 回答
如何找到精灵在团队中的位置?
9 回答
如何找到素数,但有错误。我找不到你
7 回答
如何找到素数(Python)
9 回答
如何找到索引i右侧的不同值
8 回答
如何找到索引Numpy数组时将折叠哪些轴?
1 回答
如何找到索引中的值,在列表中增加值?
6 回答
如何找到纬度/经度/高度点之间的三维距离?
8 回答
如何找到线和numpy meshgrid生成的曲面之间的交点?
6 回答
如何找到线段上距任意点最近的点?
3 回答
如何找到组中所有可能的子组
6 回答
如何找到组内值之间的最小差异
7 回答
如何找到经过训练的朴素贝叶斯分类器用于决策的单词?
8 回答
如何找到给selenium webdriver对象的文件夹名?
8 回答
如何找到给出最佳分数的列车测试分割的最佳随机状态值?
3 回答
如何找到给定Python发行版提供的模块?
8 回答
如何找到给定subversion工作副本的根文件夹
9 回答
如何找到给定一维阵列中的所有峰值?
6 回答
如何找到给定列表中的字符串组合,这些字符串加起来就是某个字符串(没有外部库)
7 回答