簡體   English   中英

Python:使用請求未完全下載文件

[英]Python: File is not fully downloaded using requests

我有問題,我的文件沒有被完全下載。 它總是從整個文件中下載幾 kb,這不是我想要的。 您是否在某處看到問題,或者我應該在那里添加更多邏輯?

謝謝

import os
import requests


def download(url: str, dest_folder: str):
    if not os.path.exists(dest_folder):
        os.makedirs(dest_folder)  # create folder if it does not exist

    filename = url.split('/')[-1].replace(" ", "_")  # be careful with file names
    file_path = os.path.join(dest_folder, filename)

    r = requests.get(url, stream=True)
    if r.ok:
        print("SUCCESS: Saving to", os.path.abspath(file_path))
        with open(file_path, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024 * 8):
                if chunk:
                    f.write(chunk)
                    f.flush()
                    os.fsync(f.fileno())
    else:  # HTTP status code 4XX/5XX
        print("Download failed: status code {}\n{}".format(r.status_code, r.text))

## EXECUTE ##
download("SOME FILE URL",
         dest_folder="SOME FOLDER)```

首先 你能試試shutil.copyfileobj來寫文件嗎? 它應該比f.write更好。

with open(file_path, 'wb') as f:
    shutil.copyfileobj(r.raw, f, length=16*1024*1024)
    f.flush()
    os.fsync(f.fileno())

第二 您可以獲得總文件大小。 如果您的文件大小不匹配,您可以重新下載您的文件。

total_content_size = int(requests.get(url, stream=True).headers['Content-Length'])

第三 這對我來說是解決問題的方法。 您應該下載在斷點處恢復的文件。 此函數將從最后一個斷點下載文件。 您可以添加一個 while 循環來執行此操作,直到文件大小完全匹配為止。

def download_file(self, url, file_path):
    file_name = url.rsplit('/', 1)[-1]
    file_full_location = file_path + "/" + file_name

    total_content_size = int(requests.get(url, stream=True).headers['Content-Length'])
    if os.path.exists(file_full_location):
        temp_size = os.path.getsize(file_full_location)
        if total_content_size == temp_size:
            return
    else:
        temp_size = 0

    headers = {'Range': 'bytes=%d-' % temp_size}
    with requests.get(url, stream = True, headers=headers) as response:
        response.raise_for_status()
        with open(file_full_location, 'ab') as f:
            shutil.copyfileobj(response.raw, f, length=16*1024*1024)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM