Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

Reply to thread

ask ko lang po san pwede po mag tanong regarding po sa python programming?



sana po ma move itong  tanong ko po doon .

thanks po


Q: how to upload file to team drive using python,

I search and use google over a month and wla prin ako makitang sagot po na maayos sana po matulugan nio po ako thanks.


i using this c0d3 as of now.




#folder location

#https://drive.google.com/drive/folders/1-Ie8LC_1ll7vw6HeM9vyOqX7quujLc34

#

from InternetConnection import connect

print(connect())

def nl():

    print("\n")   

nl()

print("This small program is created by AAC")

print("**************   Google Drive using Python *****************************")




def ModuleCheck():

       

    try:

        print("Checking required module...")

        from pydrive.auth import GoogleAuth

        from pydrive.drive import GoogleDrive

    except ModuleNotFoundError:

        print("No module found!!!")

        print("Trying to install modules...")

        __import__('os').system('pip3 install pydrive')

    except:

        print("Unkown error occured!!!")

ModuleCheck()

from pydrive.auth import GoogleAuth

from pydrive.drive import GoogleDrive

nl()





############# Connecting to Google Drive ##################

gauth = GoogleAuth()

def ConnGDrive():

    try:

        print("connecting to google drive...")

        print("Please login your account.")

       

        print("Authenticating Account...")

        # Try to load saved client credentials

        gauth.LoadCredentialsFile("mycreds.txt")

        if gauth.credentials is None:

            # Authenticate if they're not there

            gauth.LocalWebserverAuth()

        elif gauth.access_token_expired:

            # Refresh them if expired

            gauth.Refresh()

        else:

            # Initialize the saved creds

            gauth.Authorize()

        # Save the current credentials to a file

        gauth.SaveCredentialsFile("mycreds.txt")

        print("Account authenticated...")

    except:

        print("An error occured during Connecting to Account")

ConnGDrive()



gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)

nl()

########## Creating File and uploading ##################

'''

file1 = drive.CreateFile({'title': 'Hello.txt'})  # Create GoogleDriveFile instance with title 'Hello.txt'.

file1.SetContentString('Hello World!') # Set content of the file from given string.

file1.Upload()

'''

FileName = 'PYTHON LOGO.jpg'

def CreateUpload():

    try:

                   

       

        #FileName = 'H:\My Drive\tshirt design\PYTHON LOGO.jpg'

        #FileName = input = "Please enter your file name: "

           

        print('Selecting file')

        #file1 = drive.CreateFile({'title': FileName})

        print("Selected file: " + FileName)

        ans = input(f"Do you want to  upload the {FileName}? Y/N\n")

        if ans == "N" or ans == "n":

            print("Upload canceled!!! ")

           

        elif ans == "Y" or ans == "y":

           

            file1 = drive.CreateFile()

            file1.SetContentFile(FileName)

            print("uploading the file...")

            file1.Upload()

            print("Upload process finished!!! ")

           

        else:

            print("Uknown error occured. c0d3: CU")

       

    except:

        print("An error occured during uploading..")

CreateUpload()


############# Getting list of files #############

def ViewFiles():

    print("############## Getting file lists #############")

    # Auto-iterate through all files that matches this query

    try:

        file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()

        for file1 in file_list:

          print('title: %s, id: %s' % (file1['title'], file1['id']))

    except:

        print('An Error occured during listing the files')

ViewFiles()

nl()

############# Searching files #############

def SearchingFile():

    try:

        print("############# Searching files #############")

        #file_list = drive.ListFile({'q':f"title contains {Filename} and trashed=false"}).GetList()

        file_list = drive.ListFile({'q':"title contains {Filename} and trashed=false"}).GetList()

        print(file_list[0]['title']) # should be the title of the file we just created

        Myfile_id = file_list[0]['id'] # get the file ID

        print(file_id)

        return Myfile_id

    except:

        print("An error occured! SF")

nl()

####################### Download the file ################

def DownloadFile():

    try:

        file_id = SearchingFile()

        DownloadNow = input(f"Do want to download the {FileName} Y/N?")

        if DownloadNow == "y" or DownloadNow == "Y":

            try:

                file = drive.CreateFile({'id': file_id})

                #file.GetContentFile('my-awesome-file.txt') # downloads 'My Awesome File.txt' as 'my-awesome-file.txt'

                file.GetContentFile(FileName)

                print("Download complete")

            except:

                print("Download interrupted!!")

                DownloadFile()

        elif (DownloadNow == "N") or (DownloadNow == "n"):

            print("Downloading file cancelled.")

        elif (DownloadNow != "Y") or (DownloadNow != "y") or (DownloadNow != "N") or (DownloadNow != "n"):

            print("Invalid input. Please try again.")

            DownloadFile()

       

    except:

        print("An error occured during downloading!!!")


#SearchingFile()

ViewFiles()

DownloadFile()


nl()

####################### Trashing, UnTrashing, and Deleting ################

def TUD():

    try:

        file = SearchingFile()

        print("Please select number to execute the command on Google Drive.")

        print("1. Put the file in trash")

        print("2. recover the file from trash")

        print("3. permenently delete the file.")

       

        dcmd = input('......\n')

        if dcmd == 1:

            try:

                file.Trash() # put the simple file in Google Drive trash (not yet deleted)

                print("The file {FileName} has been trashed")

            except:

                print("An error  occured during trashing.")

        elif dcmd == 2:  

            try:

                file.UnTrash() # recover from trash

                print("The file {FileName} has been untrashed")

            except:

                print("An error  occured during untrashing.")

        elif dcmd == 3:

            try:

                file.Delete() # permanently delete (downloaded copy is saved)   

                print("The file {FileName} has been permanently deleted")

            except:

                print("An error  occured during permanently deleting")

    except:

        print("An error  occured during file deletion.")

    print("TUD end") 

    ViewFiles()

#TUD()


nl()

def DeleteMe():

    try:

        Dfile = SearchingFile()

        Dfile.Trash()

        print(f"File {Dfile} has been trashed")

       

    except:

        print(f"An error occured during trashing the file {Dfile}.")

    ViewFiles()

DeleteMe()


Back
Top