Как загрузить с Google Диска только файлы, которых нет на вашем компьютере, используя python

Привет, я пытаюсь загрузить файлы из папки на моем диске Google с помощью python. Я попробовал приведенный ниже сценарий из Как загрузить определенную папку Google Диска. с помощью Python?, и это работает для меня, но у меня есть много файлов в папке на моем диске Google, и я хотел бы пропустить файлы, которые уже загружены на мой компьютер. Могу ли я узнать, могу ли я сделать это возможным?

from __future__ import print_function
import pickle
import os
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaFileUpload, MediaIoBaseDownload
import io
from apiclient import errors
from apiclient import http
import logging

from apiclient import discovery

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive']


# To list folders
def listfolders(service, filid, des):
    results = service.files().list(
        pageSize=1000, q="\'" + filid + "\'" + " in parents",
        fields="nextPageToken, files(id, name, mimeType)").execute()
    # logging.debug(folder)
    folder = results.get('files', [])
    for item in folder:
        if str(item['mimeType']) == str('application/vnd.google-apps.folder'):
            if not os.path.isdir(des+"/"+item['name']):
                os.mkdir(path=des+"/"+item['name'])
            print(item['name'])
            listfolders(service, item['id'], des+"/"+item['name'])  # LOOP un-till the files are found
        else:
            downloadfiles(service, item['id'], item['name'], des)
            print(item['name'])
    return folder


# To Download Files
def downloadfiles(service, dowid, name,dfilespath):
    request = service.files().get_media(fileId=dowid)
    fh = io.BytesIO()
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
        print("Download %d%%." % int(status.progress() * 100))
    with io.open(dfilespath + "/" + name, 'wb') as f:
        fh.seek(0)
        f.write(fh.read())


def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)  # credentials.json download from drive API
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)
    # Call the Drive v3 API

    Folder_id = "'PAST YOUR SHARED FOLDER ID'"  # Enter The Downloadable folder ID From Shared Link

    results = service.files().list(
        pageSize=1000, q=Folder_id+" in parents", fields="nextPageToken, files(id, name, mimeType)").execute()
    items = results.get('files', [])
    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            if item['mimeType'] == 'application/vnd.google-apps.folder':
                if not os.path.isdir("Folder"):
                    os.mkdir("Folder")
                bfolderpath = os.getcwd()+"/Folder/"
                if not os.path.isdir(bfolderpath+item['name']):
                    os.mkdir(bfolderpath+item['name'])

                folderpath = bfolderpath+item['name']
                listfolders(service, item['id'], folderpath)
            else:
                if not os.path.isdir("Folder"):
                    os.mkdir("Folder")
                bfolderpath = os.getcwd()+"/Folder/"
                if not os.path.isdir(bfolderpath + item['name']):
                    os.mkdir(bfolderpath + item['name'])

                filepath = bfolderpath + item['name']
                downloadfiles(service, item['id'], item['name'], filepath)


if __name__ == '__main__':
    main()

person BBBBBBBB    schedule 15.04.2020    source источник
comment
Проверьте свой жесткий диск, чтобы узнать, есть ли он у вас, если вы его не загружаете? Как еще вы могли бы сделать это?   -  person DaImTo    schedule 15.04.2020
comment
Обычно хорошим подходом является разделение логики на две части. Исходный снимок вашего диска. Где вы синхронизируете большинство, если не все файлы после сканирования на наличие отсутствующих. Второй — дельта-изменения. Вы подписываетесь на изменения и применяете только те, которые не нужно постоянно сканировать. Вы делегируете задание сообщить мне, какие файлы мне нужны, другому процессу. К счастью, в drive API есть что-то похожее. Обратите внимание, что в большинстве случаев под файлами понимаются как обычные файлы, так и каталоги. Для местных часов есть inotify.   -  person edd    schedule 15.04.2020
comment
Как узнать уже загруженные файлы? По имени? В этом случае вам нужно передать имена всех уже загруженных файлов в массив, а при перечислении файлов на вашем диске - сравнить имя каждого с именами в массиве, чтобы решить, был ли он скачан. уже. Довольно сложно и, вероятно, не стоит.   -  person ziganotschka    schedule 15.04.2020
comment
тогда что, если я захочу загрузить последние файлы, загруженные на мой общий диск? нужно найти createdTime на диске Google, не так ли?   -  person BBBBBBBB    schedule 16.04.2020


Ответы (1)


Я попытался изменить части ниже, и это работает! спасибо всем, что заглянули~

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)  # credentials.json download from drive API
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)
    # Call the Drive v3 API

    Folder_id = "'PAST YOUR SHARED FOLDER ID'"  # Enter The Downloadable folder ID From Shared Link
    File_Download_Path = "'LOCATION OF THE FILES DOWNLOADED'" 

    results = service.files().list(
        pageSize=1000, q=Folder_id+" in parents", fields="nextPageToken, files(id, name, mimeType)").execute()
    items = results.get('files', [])
    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
                if not os.path.isdir(File_Download_Path):
                    os.mkdir(File_Download_Path)
                if not item['name'] in os.listdir(File_Download_Path):
                    downloadfiles(service, item['id'], item['name'], File_Download_Path)
        print("All files are downloaded.")


if __name__ == '__main__':
    main()
person BBBBBBBB    schedule 16.04.2020