簡體   English   中英

使用瀏覽器下載和使用 python-requests 庫下載有什么區別?

[英]What is the difference between download with browser and download with python-requests library?

我有一個文件位於: https : //wzy-zone.oss-cn-shanghai.aliyuncs.com/remote_disk/Cambridge/sub51050.nii.gz

當我從瀏覽器下載它時,它可以正確打開,並且可以識別為.gz文件。 在此處輸入圖片說明 但是,當我使用請求庫下載它並將其寫入本地機器時:

            full_address = os.path.join(prefix, category, name)
            print(full_address)
            response = requests.get(full_address)
            if response.status_code == 200:
                output_path = os.path.join('n4_bias', category, name)
                if not os.path.exists(output_path):
                    with open(output_path, 'wb') as f:
                        f.write(response.content)

無法正確打開,無法正確識別文件類型。 在此處輸入圖片說明 .

n4_bias/Atlanta/sub00368.nii.gz
agent = nib.load('n4_bias/Atlanta/sub00368.nii.gz')
---------------------------------------------------------------------------
ImageFileError                            Traceback (most recent call last)
<ipython-input-10-2dfc10b95c7e> in <module>()
----> 1 agent = nib.load('n4_bias/Atlanta/sub00368.nii.gz')

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/nibabel/loadsave.py in load(filename, **kwargs)
     51 
     52     raise ImageFileError('Cannot work out file type of "%s"' %
---> 53                          filename)
     54 
     55 

ImageFileError: Cannot work out file type of "n4_bias/Atlanta/sub00368.nii.gz"

那么,這兩種方法有什么區別? 我如何使用請求庫下載文件?

這個問題已經在這里回答: 下載 *.gz 壓縮文件與 python 請求損壞它

似乎requests已經自動解壓縮您的檔案。 嘗試刪除.gz文件結尾並正常打開文件。 如果可行,請更改 python 代碼以刪除.gz文件擴展名。 就像是:

with open(output_path[:-3], 'wb') as f:
    f.write(response.content)

在我將代碼更改為:

full_address = os.path.join(prefix, category, name)
response = requests.get(full_address)
output_path = os.path.join('n4_bias', category, name)
if not os.path.exists(output_path):
   with open(output_path, 'wb') as f:
        f.write(response.content)
        f.flush()

問題是最后一個代碼f.flush() ,它將改變文件點。

暫無
暫無

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

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