我正在用Python编写一个程序,它可以检测文件的移动并上传驱动器中的任何新文件(素材、音频、文件夹等),但我无法精确定位

问题描述 投票:0回答:1

这是下面的代码,尚未完全完成,但我正在上传代码,无法找到将它们上传到驱动器文件夹的文件夹中并组织等的方法。对此非常陌生。

   #Importing modules
    from __future__ import print_function
    import os,sys, os.path , time, watchdog , pickle
    import tkinter as tk
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    from watchdog.observers import Observer
    from watchdog.events import FileSystemEventHandler
    from googleapiclient.http import MediaFileUpload

    SCOPES = ['https://www.googleapis.com/auth/drive.file']
    def main():
        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(
                    'E:\V\Software\Self Made\VoltSyncFolder\VCredentials.json', SCOPES)
                creds = flow.run_local_server(port=0)

            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)
    
        # Create a Google Drive API service instance
        service = build('drive', 'v3', credentials=creds)

        # Define local file path and Google Drive folder ID
        local_file_path = r'E:\V\EVERYTHING\a.txt'

        drive_folder_id = 'the id'

        # Upload the file to Google Drive
        file_metadata = {
            'name': os.path.basename(local_file_path),
            'parents': [drive_folder_id]
        }
        media = MediaFileUpload(local_file_path, resumable=True)
        uploaded_file = service.files().create(
            body=file_metadata,
            media_body=media,
            fields='id'
        ).execute()

        print(f"File uploaded: {uploaded_file['id']}")

    if __name__ == '__main__':
        main()

    #defining functions for interconnneection from files to drive.
    '''def D_update():
    def D_delete():
    def D_rechange():'''

    #choosing files monitoring uploading (done with some drive api
    class MonitorFolder(FileSystemEventHandler):
        FILE_SIZE=1000
        def on_created(self, event):
             print(event.src_path, event.event_type)
             self.checkFolderSize(event.src_path)
             main()     
        def on_modified(self, event):
            print(event.src_path, event.event_type)
            self.checkFolderSize(event.src_path)
        
        def on_moved(self, event):
            print(event.src_path, "moved to", event.dest_path)
        
        def checkFolderSize(self,src_path):
            if os.path.isdir(src_path):
                if os.path.getsize(src_path) >self.FILE_SIZE:
                    print("Time to backup the dir")
            else:
                if os.path.getsize(src_path) >self.FILE_SIZE:
                    print("very big file")
    if __name__ == "__main__":
        src_path = 'E:\V\EVERYTHING'
    
        event_handler=MonitorFolder()
        observer = Observer()
        observer.schedule(event_handler, path=src_path, recursive=True)
        print("Monitoring started")
        observer.start()
        try:
            while(True):
               time.sleep(1)
           
        except KeyboardInterrupt:
                observer.stop()
                observer.join()
    #interfac

我尝试更改文件夹路径,但它会引发错误,指出未授予权限,因此 a.txt

还会引发错误,提示找不到文件详细信息:

"[{'message': '找不到文件: [我的驱动器文件夹 ID]。', 'domain': 'global', 'reason': 'notFound', 'location': 'fileId', 'locationType': '参数'}]">

python google-drive-api google-oauth google-api-python-client
1个回答
0
投票

我认为你的问题在于这条线

print(f"File uploaded: {uploaded_file['id']}")

尝试做

print(F'File ID: {uploaded_file.get("id")}')
© www.soinside.com 2019 - 2024. All rights reserved.