【发布时间】:2019-03-17 08:40:53
【问题描述】:
我正在阅读 McKinney 的数据分析书,他共享了 150MB 的文件。尽管Progress Bar while download file over http with Requests 已广泛讨论此主题,但我发现已接受答案中的代码引发了错误。我是初学者,所以我无法解决这个问题。
我要下载以下文件:
https://raw.githubusercontent.com/wesm/pydata-book/2nd-edition/datasets/fec/P00000001-ALL.csv
这是没有进度条的代码:
DATA_PATH='./Data'
filename = "P00000001-ALL.csv"
url_without_filename = "https://raw.githubusercontent.com/wesm/pydata-book/2nd-edition/datasets/fec"
url_with_filename = url_without_filename + "/" + filename
local_filename = DATA_PATH + '/' + filename
#Write the file on local disk
r = requests.get(url_with_filename) #without streaming
with open(local_filename, 'w', encoding=r.encoding) as f:
f.write(r.text)
这个很好用,但是因为没有进度条,不知道怎么回事。
这是改编自Progress Bar while download file over http with Requests和How to download large file in python with requests.py?的代码
#Option 2:
#Write the file on local disk
r = requests.get(url_with_filename, stream=True) # added stream parameter
total_size = int(r.headers.get('content-length', 0))
with open(local_filename, 'w', encoding=r.encoding) as f:
#f.write(r.text)
for chunk in tqdm(r.iter_content(1024), total=total_size, unit='B', unit_scale=True):
if chunk:
f.write(chunk)
第二个选项存在两个问题(即流式传输和tqdm 包):
a) 文件大小计算不正确。实际大小是 157MB,但 total_size 原来是 25MB。
b) 比 a) 更大的问题是我收到以下错误:
0%| | 0.00/24.6M [00:00<?, ?B/s] Traceback (most recent call last): File "C:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3265, in run_code
exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-31-abbe9270092b>", line 6, in <module>
f.write(data) TypeError: write() argument must be str, not bytes
作为初学者,我不确定如何解决这两个问题。我花了很多时间浏览tqdm的git页面,但我无法关注它。如有任何帮助,我将不胜感激。
我假设读者知道我们需要导入requests 和tqdm。所以,我没有包含导入这些基本包的代码。
这里是给好奇的人的代码:
with open(local_filename, 'wb') as f:
r = requests.get(url_with_filename, stream=True) # added stream parameter
# total_size = int(r.headers.get('content-length', 0))
local_filename = DATA_PATH + '/' + filename
total_size = len(r.content)
downloaded = 0
# chunk_size = max(1024*1024,int(total_size/1000))
chunk_size = 1024
#for chunk in tqdm(r.iter_content(chunk_size=chunk_size),total=total_size,unit='KB',unit_scale=True):
for chunk in r.iter_content(chunk_size=chunk_size):
downloaded += len(chunk)
a=f.write(chunk)
done = int(50 * downloaded/ total_size)
sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50 - done)))
sys.stdout.flush()
【问题讨论】:
-
想办法获取文件的真实大小和进度条很容易。
标签: python python-3.x csv python-requests