【问题标题】:how to use colab so that it recognize a folder of my Google Drive如何使用 colab 使其识别我的 Google Drive 的文件夹
【发布时间】:2021-08-04 02:15:37
【问题描述】:

我已经下载了 IMDB 数据集并将其复制到我的 Google Drive 中的 imdb 文件夹下,我遇到的问题是我无法在 colab 下操作此文件夹。据说它在我的驱动器中,并查看了我已完成以下操作的解决方案:

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

它要求输入验证码,我已经输入了。但是,当我执行以下操作时:

imdb="imdb"
trainD=os.path.join(imdb,"train")
testD=os.path.join(imdb,"test")
testlabels=[]
testtexts=[]
print(trainD)
trainlabels=[]
traintexts=[]
for labelType in ["neg","pos"]:
  dirName=os.path.join(trainD,labelType)
  print(dirName)
  for fName in os.listdir(dirName):
    if fName[-4:]==".txt":
      f=open(os.path.join(dirName,fName),encoding="utf8")
      print(f)

出现如下错误:

检查模块中的 RROR:root:Internal Python 错误。 以下是此内部错误的回溯。

imdb/train
imdb/train/neg
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-26-a6dd3dffb70e>", line 12, in <module>
    for fName in os.listdir(dirName):
OSError: [Errno 107] Transport endpoint is not connected: 'imdb/train/neg'

但是,可以使用以下子文件夹:train 和 test。我可以使用 Anaconda 在本地驱动器中读取这些文件夹,但不能在 Colab 中读取。有什么帮助吗?

【问题讨论】:

  • 在左侧,您可以看到您正在使用的文件夹结构。Google 驱动器连接在 /content/drive,因此您需要为驱动器中所有文件和文件夹的所有路径使用此前缀.如果您想更改为“在您的驱动器中”工作,即例如open("foo.txt") 会自动打开/content/drive/foo.txt,你可以做import os; os.chdir('/content/drive') (chdir = 改变工作目录)。

标签: python google-colaboratory


【解决方案1】:
  1. 运行下面的代码后,你会得到认证Url,必须登录 登录后使用谷歌帐户获取代码然后粘贴到框中。

    from google.colab import drive
    drive.mount('/content/drive') 
    
  2. 对路径上的代码稍作改动,也许这对你有帮助:

    imdb="/content/drive/MyDrive/imdb"
    trainD=os.path.join(imdb,"train")
    testD=os.path.join(imdb,"test")
    testlabels=[]
    testtexts=[]
    print(trainD)
    trainlabels=[]
    traintexts=[]
    for labelType in ["neg","pos"]:
      dirName=os.path.join(trainD,labelType)
      print(dirName)
      for fName in os.listdir(dirName):
        if fName[-4:]==".txt":
          f=open(os.path.join(dirName,fName),encoding="utf8")
          print(f)
    

【讨论】:

    【解决方案2】:

    我想您应该使用绝对路径来访问您云端硬盘上的内容,这就是您无法打开文本文件的原因。尝试将 imdb 变量的值替换为:

    "/content/drive/MyDrive/path_to_your_imdb_folder/..."
    

    不要忘记在 MyDrive 文件夹之后配置路径。

    我希望它会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-16
      • 2022-08-20
      • 1970-01-01
      • 2020-10-01
      • 2018-10-22
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多