python - 如何自动将文件生成到与我的 Colab 笔记本相同的 Google Drive 文件夹?

标签 python google-drive-api google-colaboratory

我正在一个简单的维基百科转储文件上执行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 脚本生成文件并将它们放在同一个文件夹中作为我的脚本。任何帮助,将不胜感激。谢谢!

最佳答案

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

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

关于python - 如何自动将文件生成到与我的 Colab 笔记本相同的 Google Drive 文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55306714/

相关文章:

python - 在 Python 中从字符串中去除数字

python - 如何在Python中使用XPath选择兄弟节点的子节点?

unix - 带有 FUSE 的 Google 云端硬盘

jupyter-notebook - 如何在 Google Colab 中打开文本文件

python - django 的 url 正则表达式如何工作

Python 多处理队列管理器地址已在使用中

javascript - 谷歌驱动器iframe编辑

java - Google Drive API 访问我自己的帐户

keras - 设置 Google Colab 使用 Theano 作为后端

python - 来自 "ImportError: cannot import name ' 的变压器 : Error importing packages. 'torch.optim.lr_scheduler' SAVE_STATE_WARNING'