【问题标题】:How do I automatically generate files to the same google drive folder as my colab notebook?如何自动将文件生成到与我的 colab 笔记本相同的 google drive 文件夹中?
【发布时间】:2019-08-13 20:37:29
【问题描述】:

我正在对一个简单的维基百科转储文件执行 LDA,但我遵循的代码需要将文章输出到文件。我需要一些指导,因为 python 和 colab 非常广泛,我似乎无法找到这个特定问题的答案。这是我安装谷歌驱动器的代码:

!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

# Authenticate the user
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

# Get your file
fileId ='xxxx'
fileName = 'simplewiki-20170820-pages-meta-current-reduced.xml'
downloaded = drive.CreateFile({'id': fileId})
downloaded.GetContentFile(fileName)

这是罪魁祸首,这段代码试图从文章中创建一个文件

if not article_txt == None and not article_txt == "" and len(article_txt) > 150 and is_ascii(article_txt):
                            outfile = dir_path + str(i+1) +"_article.txt"
                            f = codecs.open(outfile, "w", "utf-8")
                            f.write(article_txt)
                            f.close()
                            print (article_txt)

我已经尝试了很多东西,但我想不起来了。基本上,我需要知道的是如何转换此代码,以便它可以与谷歌驱动器一起使用。几个小时以来,我一直在尝试很多解决方案。我记得做的事情是将这段代码转换成这个

file_obj = drive.CreateFile()
file_obj['title'] = "file name"

但后来我得到一个错误“预期的 str、字节或 os.PathLike 对象,而不是 GoogleDriveFile”。这不是如何上传文件并使用 colab 打开它的问题,因为我已经知道如何使用 XML 文件执行此操作,我需要知道的是如何通过我的 colab 脚本生成文件并将它们放在同一个文件夹中作为我的脚本。任何帮助,将不胜感激。谢谢!

【问题讨论】:

    标签: python google-drive-api google-colaboratory


    【解决方案1】:

    我不确定问题是生成文件还是将它们复制到谷歌驱动器,如果是后者,更简单的方法是将驱动器直接挂载到实例,如下所示

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

    然后您可以像访问硬盘一样访问驱动器中的任何项目并使用 bash 命令复制文件:

    !cp filename 'drive/My Drive/folder1/'
    

    另一种选择是使用shutil

    import shutil
    
    shutil.copy(filename, 'drive/My Drive/folder1/')
    

    【讨论】:

      猜你喜欢
      • 2018-10-22
      • 2020-10-01
      • 2022-08-20
      • 2018-11-11
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多