【问题标题】:How do I iterate through multiple text(.txt) files in a folder on Google Drive to upload on Google Colab?如何遍历 Google Drive 文件夹中的多个文本(.txt)文件以上传到 Google Colab?
【发布时间】:2021-10-22 04:26:20
【问题描述】:

我在 Google Drive 上有一个包含多个文本文件的文件夹。我想通过遍历文件夹中的每个文件将它们上传到 Google colab。如果有人能帮我解决这个问题那就太好了

【问题讨论】:

  • 抱歉,SO 不是编码服务。请编辑您的问题并向我们展示您的尝试,并描述您在当前解决方案中遇到的任何问题。

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


【解决方案1】:

您需要位于同一文件夹中的 listOfFileNames.txt 文件;例如,我有一个 listOfDates.txt 文件,其中存储了以日期为标题的文件名。

import numpy as np
import pandas pd

#listOfFilesNames = ['8_26_2021', '8_27_2021', '8_29_2021', '8_30_2021']
savedListOfFileNames = pd.read_csv('listOfFilesNames.txt', header = None).copy()
emptyVectorToStoreAllOfTheData = []
listOfFileNames = []
for iteratingThroughFileNames in range(len(savedListOfFileNames)):
  listOfFileNames.append(savedListOfFileNames[0][iteratingThroughFileNames])

for iteratingThroughFileNames in range(len(listOfFileNames)):
  currentFile = pd.read_csv(listOfFileNames[0][iteratingThroughFileNames] + '.txt').copy()
  for iteratingThroughCurrentFile in range(len(currentFile)):
    emptyVectorToStoreAllOfTheData.append(currentFile[0][iteratingThroughCurrentfile])

如果您不知道如何访问您的文件夹和文件,那么您需要 (1) 挂载您的驱动器并 (2) 定义一个 createWorkingDirectoryFunction:

import os
from google.colab import drive
myGoogleDrive = drive.mount('/content/drive', force_remount = True)
def createWorkingDirectoryFunction(projectFolder, rootDirectory):
  if os.path.isdir(rootDirectory + projectFolder) == False:
    os.mkdir(rootDirectory + projectFolder)
  os.chdir(rootDirectory + projectFolder)

projectFolder = '/folderContainingMyFiles/' # Folder you want to access and/or create
rootDirectory = '/content/drive/My Drive/Colab Notebooks'
createWorkingDirectoryFunction(projectFolder, rootDirectory)

【讨论】:

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