Search code examples
pythonpathgoogle-colaboratory

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.

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?

My Python version is 3.6.9.


Solution

  • Use {varname} syntax to pass Python variables into the 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.

    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)