[英]Convert string to path to use it with Unzip in Google Colaboratory
I'm working with a Jupyter notebook in Google Colaboratory and I want to unzip file that it is on my Google Drive into /tmp folder.我正在 Google Colaboratory 中使用 Jupyter 笔记本,我想将 Google Drive 上的文件解压缩到 /tmp 文件夹中。
I have tried this:我试过这个:
import os
root_dir = '/tmp/omniglot/data/'
!unzip '/content/gdrive/My Drive/Colab Notebooks/data/omniglot.zip' -d path.path(root_dir)
But I get the error:但我收到错误:
syntax error near unexpected token `('意外标记“(”附近的语法错误
I have also tried:我也试过:
from pathlib import Path
root_dir = '/tmp/omniglot/data/'
!unzip '/content/gdrive/My Drive/Colab Notebooks/data/omniglot.zip' -d Path(str_path)
But I get the same error.但我得到了同样的错误。
How can I use the string root_dir
with unzip?如何将字符串root_dir
与 unzip 一起使用?
My Python version is 3.6.9.我的 Python 版本是 3.6.9。
This is how I do it (without using !unzip
command):这就是我的做法(不使用!unzip
命令):
import os
import zipfile
from pathlib import Path
# Create destination folder if it doesn't exist.
Path(root_dir).mkdir(parents=True, exist_ok=True)
local_zip = '/content/gdrive/My Drive/Colab Notebooks/data/omniglot.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall(root_dir)
zip_ref.close()
Use {varname}
syntax to pass Python variables into the shell.使用{varname}
语法将 Python 变量传递到 shell。
import os
root_dir = '/tmp/omniglot/data/'
os.makedirs(root_dir, exist_ok=True) # Create a target directory if doesn't exist
!unzip '/content/gdrive/My Drive/Colab Notebooks/data/omniglot.zip' -d {root_dir}
You can also use zipfile from standard library.您还可以使用标准库中的 zipfile。
import zipfile
root_dir = '/tmp/omniglot/data/'
zip_file = '/content/gdrive/My Drive/Colab Notebooks/data/omniglot.zip'
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
zip_ref.extractall(root_dir)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.