AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / unix / 问题 / 765336
Accepted
Franck Dernoncourt
Franck Dernoncourt
Asked: 2023-12-22 06:22:57 +0800 CST2023-12-22 06:22:57 +0800 CST 2023-12-22 06:22:57 +0800 CST

如何下载非常大的 URL 列表,以便将下载的文件分成包含文件名首字母的子文件夹?

  • 772

我想下载很多文件(>数千万)。我有每个文件的 URL。我的文件中有 URL 列表URLs.txt:

http://mydomain.com/0wd.pdf
http://mydomain.com/asz.pdf
http://mydomain.com/axz.pdf
http://mydomain.com/b00.pdf
http://mydomain.com/bb0.pdf
etc.

我可以通过下载它们wget -i URLs.txt,但是它会超过一个文件夹中可以放置的最大文件数。

如何下载这么大的 URL 列表,以便将下载的文件分成包含文件名首字母的子文件夹?例如,:

0/0wd.pdf
a/asz.pdf
a/axz.pdf
b/b00.pdf
b/bb0.pdf
etc.

如果这很重要的话,我使用 Ubuntu。

wget
  • 2 2 个回答
  • 45 Views

2 个回答

  • Voted
  1. Best Answer
    larsks
    2023-12-22T10:19:29+08:002023-12-22T10:19:29+08:00

    也许是这样的:

    awk -F/ '{print substr($NF, 1, 1), $0}' urls.txt |
      xargs -L1 bash -c 'mkdir -p -- "$0" && curl -sSF -O --output-dir "$0" "$1"'
    

    在每行前面awk加上文件名的第一个字符,然后使用该字符在curl命令中选择输出目录。您可以使用-PGNU 实现的选项xargs来并行运行多个提取。

    假设 URL 不包含空格、引号或反斜杠,但 URL 不应包含 URI 编码以外的内容(即使curl能够处理它们并自行进行 URI 编码)。

    给定您的示例输入,运行上述命令会产生:

    .
    ├── 0
    │   └── 0wd.pdf
    ├── a
    │   ├── asz.pdf
    │   └── axz.pdf
    └── b
        ├── b00.pdf
        └── bb0.pdf
    
    • 1
  2. Franck Dernoncourt
    2023-12-24T07:34:52+08:002023-12-24T07:34:52+08:00

    ChatGPT 提供了一些 Python 中的工作代码(我确认它适用于 Python 3.11):

    import os import requests
    
    def download_files_with_subfolders(url_file):
        with open(url_file, 'r') as file:
            for url in file:
                url = url.strip()
                filename = os.path.basename(url)
                first_letter = filename[0]
    
                # Create subfolder if it doesn't exist
                subfolder = os.path.join(first_letter, '')
                os.makedirs(subfolder, exist_ok=True)
    
                # Download the file
                response = requests.get(url)
                if response.status_code == 200:
                    file_path = os.path.join(subfolder, filename)
                    with open(file_path, 'wb') as file:
                        file.write(response.content)
                    print(f"Downloaded: {url} -> {file_path}")
                else:
                    print(f"Failed to download: {url} (Status code: {response.status_code})")
    
    if __name__ == "__main__":
        urls_file = "somefile.txt"
        download_files_with_subfolders(urls_file) 
    

    包含somefile.txt:

    http://mydomain.com/0wd.pdf
    http://mydomain.com/asz.pdf
    http://mydomain.com/axz.pdf
    http://mydomain.com/b00.pdf
    http://mydomain.com/bb0.pdf
    etc.
    

    更高级的变体:

    1. 保留响应标头中的最后修改日期(代码也主要来自 ChatGPT):
    import requests
    import os
    from datetime import datetime
    
    def download_file(url, local_filename):
        # Send a GET request to the server
        response = requests.get(url, stream=True)
    
        # Check if the request was successful (status code 200)
        if response.status_code == 200:
            # Get the last modified date from the response headers
            last_modified_header = response.headers.get('Last-Modified')
            last_modified_date = datetime.strptime(last_modified_header, '%a, %d %b %Y %H:%M:%S %Z')
    
            # Save the content to a local file while preserving the original date
            with open(local_filename, 'wb') as f:
                for chunk in response.iter_content(chunk_size=128):
                    f.write(chunk)
    
            # Set the local file's last modified date to match the original date
            os.utime(local_filename, (last_modified_date.timestamp(), last_modified_date.timestamp()))
    
            print(f"Downloaded {local_filename} with the original date {last_modified_date}")
        else:
            print(f"Failed to download file. Status code: {response.status_code}")
    
    
    def download_files_with_subfolders(url_file):
        with open(url_file, 'r') as file:
            for url in file:
                url = url.strip()
                filename = os.path.basename(url)
                first_letter = filename[0]
    
                # Create subfolder if it doesn't exist
                subfolder = os.path.join(first_letter, '')
                os.makedirs(subfolder, exist_ok=True)
    
                file_path = os.path.join(subfolder, filename)
                download_file(url, file_path)
    
    if __name__ == "__main__":
        urls_file = "somefile.txt"
        download_files_with_subfolders(urls_file)
    
    1. 多线程下载:
    import requests
    import os
    from datetime import datetime
    
    from multiprocessing.dummy import Pool as ThreadPool
    
    def download_file(url, local_filename):
        # Send a GET request to the server
        response = requests.get(url, stream=True)
    
        # Check if the request was successful (status code 200)
        if response.status_code == 200:
            # Get the last modified date from the response headers
            last_modified_header = response.headers.get('Last-Modified')
            last_modified_date = datetime.strptime(last_modified_header, '%a, %d %b %Y %H:%M:%S %Z')
    
            # Save the content to a local file while preserving the original date
            with open(local_filename, 'wb') as f:
                for chunk in response.iter_content(chunk_size=128):
                    f.write(chunk)
    
            # Set the local file's last modified date to match the original date
            os.utime(local_filename, (last_modified_date.timestamp(), last_modified_date.timestamp()))
    
            print(f"Downloaded {local_filename} with the original date {last_modified_date}")
        else:
            print(f"Failed to download file. Status code: {response.status_code}")
    
    
    def download_files_with_subfolders(url_file, num_threads=4):
        download_arguments = []
        with open(url_file, 'r') as file:
            for url in file:
                url = url.strip()
                filename = os.path.basename(url)
                first_letter = filename[0]
    
                # Create subfolder if it doesn't exist
                subfolder = os.path.join(first_letter, '')
                os.makedirs(subfolder, exist_ok=True)
    
                file_path = os.path.join(subfolder, filename)
                download_arguments.append((url, file_path))
    
        pool = ThreadPool(num_threads)
        results = pool.starmap(download_file, download_arguments)
    
    
    if __name__ == "__main__":
        urls_file = "somefile.txt"
        download_files_with_subfolders(urls_file, num_threads=10)
    
    1. 为第一个字母创建一个文件夹,为第二个字母创建一个子文件夹。例如,:
    0/w/0wd.pdf
    a/s/asz.pdf
    a/x/axz.pdf
    b/0/b00.pdf
    b/b/bb0.pdf
    etc.
    

    代码:

    import requests
    import os
    from datetime import datetime
    
    from multiprocessing.dummy import Pool as ThreadPool
    
    def download_file(url, local_filename):
        # Send a GET request to the server
        response = requests.get(url, stream=True)
    
        # Check if the request was successful (status code 200)
        if response.status_code == 200:
            # Get the last modified date from the response headers
            last_modified_header = response.headers.get('Last-Modified')
            last_modified_date = datetime.strptime(last_modified_header, '%a, %d %b %Y %H:%M:%S %Z')
    
            # Save the content to a local file while preserving the original date
            with open(local_filename, 'wb') as f:
                for chunk in response.iter_content(chunk_size=128):
                    f.write(chunk)
    
            # Set the local file's last modified date to match the original date
            os.utime(local_filename, (last_modified_date.timestamp(), last_modified_date.timestamp()))
    
            print(f"Downloaded {local_filename} with the original date {last_modified_date}")
        else:
            print(f"Failed to download file. Status code: {response.status_code}")
    
    
    def download_files_with_subfolders(url_file, num_threads=4):
        download_arguments = []
        with open(url_file, 'r') as file:
            for url in file:
                url = url.strip()
                filename = os.path.basename(url)
                first_letter = filename[0]
                second_letter = filename[1]
    
                # Create subfolder if it doesn't exist
                subfolder = os.path.join(first_letter, '')
                os.makedirs(subfolder, exist_ok=True)
                subsubfolder = os.path.join(first_letter, second_letter)
                os.makedirs(subsubfolder, exist_ok=True)
    
                file_path = os.path.join(subsubfolder, filename)
                download_arguments.append((url, file_path))
    
        pool = ThreadPool(num_threads)
        results = pool.starmap(download_file, download_arguments)
    
    
    if __name__ == "__main__":
        urls_file = "somefile.txt"
        download_files_with_subfolders(urls_file, num_threads=10)
    
    • -1

相关问题

  • Debian 测试 wget 段错误

  • 从 Ubuntu Server 存储库制作镜像的疑问

  • 没有使用“wget -r”获取文件

  • wget 在递归模式下不起作用

  • 如何在终端中下载链接重定向并且似乎仅在 GUI 中工作的文件?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    模块 i915 可能缺少固件 /lib/firmware/i915/*

    • 3 个回答
  • Marko Smith

    无法获取 jessie backports 存储库

    • 4 个回答
  • Marko Smith

    如何将 GPG 私钥和公钥导出到文件

    • 4 个回答
  • Marko Smith

    我们如何运行存储在变量中的命令?

    • 5 个回答
  • Marko Smith

    如何配置 systemd-resolved 和 systemd-networkd 以使用本地 DNS 服务器来解析本地域和远程 DNS 服务器来解析远程域?

    • 3 个回答
  • Marko Smith

    dist-upgrade 后 Kali Linux 中的 apt-get update 错误 [重复]

    • 2 个回答
  • Marko Smith

    如何从 systemctl 服务日志中查看最新的 x 行

    • 5 个回答
  • Marko Smith

    Nano - 跳转到文件末尾

    • 8 个回答
  • Marko Smith

    grub 错误:你需要先加载内核

    • 4 个回答
  • Marko Smith

    如何下载软件包而不是使用 apt-get 命令安装它?

    • 7 个回答
  • Martin Hope
    user12345 无法获取 jessie backports 存储库 2019-03-27 04:39:28 +0800 CST
  • Martin Hope
    Carl 为什么大多数 systemd 示例都包含 WantedBy=multi-user.target? 2019-03-15 11:49:25 +0800 CST
  • Martin Hope
    rocky 如何将 GPG 私钥和公钥导出到文件 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Evan Carroll systemctl 状态显示:“状态:降级” 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim 我们如何运行存储在变量中的命令? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S 为什么 /dev/null 是一个文件?为什么它的功能不作为一个简单的程序来实现? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 如何从 systemctl 服务日志中查看最新的 x 行 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - 跳转到文件末尾 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla 为什么真假这么大? 2018-01-26 12:14:47 +0800 CST
  • Martin Hope
    Christos Baziotis 在一个巨大的(70GB)、一行、文本文件中替换字符串 2017-12-30 06:58:33 +0800 CST

热门标签

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve