python 使用colab notebook从公共谷歌驱动器中提取Zip文件

92vpleto  于 2024-01-05  发布在  Python
关注(0)|答案(1)|浏览(129)

我想从一个公共的google drive文件夹下载一个数据集(保存为zip)。
第一个月
因为我希望它可以被其他人复制,所以我不想将它复制到我的驱动器上(最好也不要将我的驱动器挂载到笔记本电脑中)。
如何才能做到这一点?
到目前为止,我试过:

  1. import requests
  2. import io
  3. import zipfile
  4. zip_url = 'https://drive.google.com/file/d/1fdFu5NGXe4rTLYKD5wOqk9dl-eJOefXo'
  5. response = requests.get(zip_url)
  6. file_contents = io.BytesIO(response.content)
  7. print(file_contents)
  8. with zipfile.ZipFile(file_contents, 'r') as zip_ref:
  9. zip_ref.extractall('/content/') # Replace with your desired extraction path

字符串
但是得到这个错误(并在之前打印“file_contents”):

  1. <_io.BytesIO object at 0x7ad7efbf27f0>
  2. ---------------------------------------------------------------------------
  3. BadZipFile Traceback (most recent call last)
  4. <ipython-input-18-56d2c8f2bfe8> in <cell line: 14>()
  5. 12 print(file_contents)
  6. 13 # Extract the zip file (if needed)
  7. ---> 14 with zipfile.ZipFile(file_contents, 'r') as zip_ref:
  8. 15 zip_ref.extractall('/content/') # Replace with your desired extraction path
  9. 1 frames
  10. /usr/lib/python3.10/zipfile.py in _RealGetContents(self)
  11. 1334 raise BadZipFile("File is not a zip file")
  12. 1335 if not endrec:
  13. -> 1336 raise BadZipFile("File is not a zip file")
  14. 1337 if self.debug > 1:
  15. 1338 print(endrec)
  16. BadZipFile: File is not a zip file


如果我尝试以下方法,我会得到一个空的zip文件:

  1. file_id = '1fdFu5NGXe4rTLYKD5wOqk9dl-eJOefXo'
  2. download_url = f'https://drive.google.com/uc?export=download&id={file_id}'
  3. !wget --no-check-certificate -O '/content/file.zip' 'https://drive.google.com/uc?export=download&id=1fdFu5NGXe4rTLYKD5wOqk9dl-eJOefXo'


任何帮助将不胜感激。

vjrehmav

vjrehmav1#

返回的内容类型是html而不是zip文件。

  1. import requests
  2. import io
  3. file_id = '1fdFu5NGXe4rTLYKD5wOqk9dl-eJOefXo'
  4. download_url = f'https://drive.google.com/uc?export=download&id={file_id}'
  5. response = requests.get(download_url)
  6. print(response.headers.get("Content-Type"))

字符串
这应该告诉你服务器返回的内容。在这种情况下,它的文本/html,这不是一个zip文件。
检查URL是否指向实际的zip文件。

相关问题