4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python で複数ファイルを同時にダウンロードする

Last updated at Posted at 2025-12-06

概要

インターネット上のファイルを複数同時にダウンロードするための Python プログラムを書いたので,備忘録的に残しておく.

詳細

書いたプログラム

download.py
import os.path
import urllib.error
import urllib.request

def download():
    # ファイルURLの読み込み
    with open("urls.txt") as file:
        urls = [url.strip() for url in file.readlines()]

    # ファイルのダウンロード
    print("Downloading...")
    for url in urls:
        filename = os.path.basename(url)
        try:
            urllib.request.urlretrieve(url, filename)
            print(f"Downloaded: {url} -> {filename}")
        except urllib.error.HTTPError:
            # ダウンロードできなかったファイルURLを表示
            print(f"Error: {url}")

    print("Finished!")

if __name__ == "__main__":
    download()

使い方

事前準備

同一ディレクトリに次の2つのファイルを作成する.

  • download.py (先述のプログラム)
  • urls.txt

urls.txt には,ダウンロードしたいファイルのURLを以下のように1行1URLずつ記載する.

urls.txt
https://example.com/sample.txt
https://example.com/picture.jpg
https://example.com/program.py

プログラム実行

download.py を実行することでダウンロードが行われる.
ダウンロードされたファイルも同一ディレクトリに保存される.

C:\Users\denkiuo604>py download.py
Downloading...
Downloaded: https://example.com/sample.txt -> sample.txt
Downloaded: https://example.com/picture.jpg -> picture.jpg
Downloaded: https://example.com/program.py -> program.py
Finished!

もしダウンロードに失敗した場合は Error: (失敗したURL) と表示される.
例えば,https://example.com/picture.jpg のダウンロードのみ失敗した場合は次のような結果になる.

C:\Users\denkiuo604>py download.py
Downloading...
Downloaded: https://example.com/sample.txt -> sample.txt
Error: https://example.com/picture.jpg
Downloaded: https://example.com/program.py -> program.py
Finished!
4
0
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
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?