How does python read data from google drive?

from __future__ import print_function

import pickle

import os.path

import io

import shutil

import requests

from mimetypes import MimeTypes

from googleapiclient.discovery import build

from google_auth_oauthlib.flow import InstalledAppFlow

from google.auth.transport.requests import Request

from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload

class DriveAPI:

    global SCOPES

    def __init__[self]:

        self.creds = None

        if os.path.exists['token.pickle']:

            with open['token.pickle', 'rb'] as token:

                self.creds = pickle.load[token]

        if not self.creds or not self.creds.valid:

            if self.creds and self.creds.expired and self.creds.refresh_token:

                self.creds.refresh[Request[]]

            else:

                flow = InstalledAppFlow.from_client_secrets_file[

                    'credentials.json', SCOPES]

                self.creds = flow.run_local_server[port=0]

            with open['token.pickle', 'wb'] as token:

                pickle.dump[self.creds, token]

        self.service = build['drive', 'v3', credentials=self.creds]

        results = self.service.files[].list[

            pageSize=100, fields="files[id, name]"].execute[]

        items = results.get['files', []]

        print["Here's a list of files: \n"]

        print[*items, sep="\n", end="\n\n"]

    def FileDownload[self, file_id, file_name]:

        request = self.service.files[].get_media[fileId=file_id]

        fh = io.BytesIO[]

        downloader = MediaIoBaseDownload[fh, request, chunksize=204800]

        done = False

        try:

            while not done:

                status, done = downloader.next_chunk[]

            fh.seek[0]

            with open[file_name, 'wb'] as f:

                shutil.copyfileobj[fh, f]

            print["File Downloaded"]

            return True

        except:

            print["Something went wrong."]

            return False

    def FileUpload[self, filepath]:

        name = filepath.split['/'][-1]

        mimetype = MimeTypes[].guess_type[name][0]

        file_metadata = {'name': name}

        try:

            media = MediaFileUpload[filepath, mimetype=mimetype]

            file = self.service.files[].create[

                body=file_metadata, media_body=media, fields='id'].execute[]

            print["File Uploaded."]

        except:

            raise UploadError["Can't Upload File."]

if __name__ == "__main__":

    obj = DriveAPI[]

    i = int[input["Enter your choice:

                  "1 - Download file, 2- Upload File, 3- Exit.\n"]]

    if i == 1:

        f_id = input["Enter file id: "]

        f_name = input["Enter file name: "]

        obj.FileDownload[f_id, f_name]

    elif i == 2:

        f_path = input["Enter full file path: "]

        obj.FileUpload[f_path]

    else:

        exit[]

How does Python read files from Google Drive?

1] Install PyDrive. The first step is to install PyDrive. ... .
2] Authenticate. The second step is to authenticate and create a PyDrive client..
3] Authorizing. ... .
4] Generating a shareable link. ... .
5] Getting the file_id. ... .
6] Load the CSV. ... .
7] Showing the Results..

How send files from Google Drive to Python?

Pre-Requisites..
Step 1: Import the libraries..
Step 2: OAuth made easy..
Step 3 : Upload files to your Google Drive..
Step 4: List out files from Google Drive..
Step 5: Download the files from Google Drive..
Step 6: Create the Text files in Google Drive..
Step 7: Read the content of the text file directly from Google Drive..

Can I run Python from Google Drive?

The Google Colaboratory [“Colab”] is a notebook [like a Jupyter Notebook] where you can run Python code in your Google Drive. You can write text, write code, run that code, and see the output – all in line in the same notebook.

How do you read a CSV file from Google Drive in Google Colab?

After you allow permission, copy the given verification code and paste it in the box in Colab. Once you have completed verification, go to the CSV file in Google Drive, right-click on it and select “Get shareable link”. The link will be copied into your clipboard. Paste this link into a string variable in Colab.

Bài mới nhất

Chủ Đề