5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PythonのRequestsでサイズの大きいファイルをダウンロード

Last updated at Posted at 2023-02-17

Pythonのrequestsモジュールでファイルをダウンロードしたいとする。素直に書くとこう。

import requests
r = requests.get('https://hogehoge/')
with open('hogehoge.zip', 'wb') as f:
  f.write(r.content)

ただ、これではファイル全体をメモリに読み込むため、サイズの大きなファイルをダウンロードしようとしてメモリが足りなくなることがあった。
そんなときは、ストリームを使って少しずつ読み書きすればよい。次の例では1MBずつ処理する。

import requests
with requests.get('https://hogehoge/', stream=True) as r:
  with open('hogehoge.zip', 'wb') as f:
    for chunk in r.iter_content(chunk_size=1024*1024):
      f.write(chunk)

参考: Requests / Advanced Usage / Body Content Workflow

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?