Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing files on google colab

i'm using Google Colaboratory IPython to do style transfer, after mounting my drive by running:

from google.colab import drive
drive.mount('/drive')

It was mounted, so i tried to cd into a directory, show the pwd and ls but it doesn't display the correct pwd

!cd "/content/drive/My Drive/"
!pwd
!ls

but it won't cd into the directory given, it only cd into 'content/'

also when i tried accessing some images using a "load_image() function in my code like below

def load_image(img_path, max_size=400, Shape=None):
    image = Image.open(img_path).convert('RGB')
    if max(image.size) > max_size:
        size = max_size
    else:
        size = max(image.size)

    if shape is not None:
        size = shape

    in_transform = transforms.Compose([transforms.Resize(size),
                    transforms.ToTensor(),
                    transforms.Normalize((0.485, 0.456, 0.406), 
                                         (0.229, 0.224, 0.225))])

    image = in_transform(image)[:3,:,:].unsqueeze(0)

    return image
#load image content
content = load_image('content/drive/My Drive/uche.jpg')
style = load_image('content/drive/My Drive/uche.jpg')

But this code throws an error when i tried to load image from the directory saying:

FileNotFoundError: [Errno 2] No such file or directory: 'content/drive/My Drive/uche.jpg'

like image 240
Akano Benjamin Avatar asked Mar 05 '23 20:03

Akano Benjamin


1 Answers

Short answer: To change the working directory, use %cd or os.chdir rather than !cd.

The back-story is that ! commands are executed in a subshell, with its own independent working directory from the Python process running your code. But, what you want is to change the working directory of the Python process. That's what os.chdir will do, and %cd is a convenient alias that works in notebooks.

Putting it together, I think you want to write:

from google.colab import drive
drive.mount('/content/drive')
%cd /content/drive/My\ Drive
like image 114
Bob Smith Avatar answered Mar 27 '23 06:03

Bob Smith