首页 > 解决方案 > 访问 google colab 上的文件

问题描述

在通过运行安装驱动器后,我正在使用 Google Colaboratory IPython 进行样式转换:

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

它已安装,所以我尝试 cd 进入一个目录,显示 pwd 和 ls 但它没有显示正确的 pwd

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

但它不会 cd 进入给定的目录,它只会 cd 进入 'content/'

当我尝试在我的代码中使用“load_image() 函数访问一些图像时,如下所示

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')

但是当我尝试从目录加载图像时,这段代码会引发错误:

FileNotFoundError:[Errno 2] 没有这样的文件或目录:'content/drive/My Drive/uche.jpg'

标签: conv-neural-networkgoogle-colaboratorystyle-transfer

解决方案


简短回答:要更改工作目录,请使用%cdoros.chdir而不是!cd.

背后的故事是!命令在一个子shell中执行,它有独立于运行代码的Python进程的工作目录。但是,您想要的是更改 Python 进程的工作目录。这就是os.chdir将要做的,并且%cd是在笔记本中工作的方便别名。

放在一起,我想你想写:

from google.colab import drive
drive.mount('/content/drive')
%cd /content/drive/My\ Drive

推荐阅读