Create new folder on Gdrive using pydrive module - python

Trying to create folder on google drive using pydrive:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
Authentication works, I can download some files from my drive, etc.
But can't figure out, how to create new folder. I'm trying:
folder_id = 'parent_folder_id'
file_metadata = {
'name': 'test_folder',
'parents': [folder_id],
'mimeType': 'application/vnd.google-apps.folder'
}
file = drive.files().create(body=file_metadata, fields='id').execute()
This gives error: 'GoogleDrive' object has no attribute 'files'
Seems i missing something from docs, not sure what exactly though.
Any help appreciated.

class Google_Drive:
def __init__(self, folder_id):
self.gauth = GoogleAuth()
self.gauth.LocalWebserverAuth()
self.drive = GoogleDrive(self.gauth)
self.folder_id = folder_id
def create_folder(self, folderName):
file_metadata = {
'title': folderName,
'parents': [{'id': self.folder_id}], #parent folder
'mimeType': 'application/vnd.google-apps.folder'
}
folder = self.drive.CreateFile(file_metadata)
folder.Upload()

The python sample code that is used in the create folder example uses google-api-python-client based on the Python Quickstart, You can refer to this Drive API documentation for the list of methods available in google-api-python-client.
pydrive has a different methods used for Creating and updating file. You need to use CreateFile(metadata) to create an instance of GoogleDriveFile then use Upload()
Sample Code:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
folder_id = 'parent_folder_id'
file_metadata = {
'name': 'test_folder',
'parents': [folder_id],
'mimeType': 'application/vnd.google-apps.folder'
}
folder = drive.CreateFile(file_metadata)
folder.Upload()
Additional Reference:
TO CREATE A NEW FOLDER IN GOOGLE DRIVE THROUGH PYTHON SCRIPT USING PYDRIVE MODULE

Related

Why can't download from shared with me in google drive

I am trying to download files from shared with me in google drive. But unable to implement. When I download from my drive, its working fine. If you guys have any idea how to implement it, would help alot :)
Code:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import streamlit as st
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
path = "/home/lungsang/Desktop/levelpack-UI/content/A0/1 docx-raw/"
folder = "1tuQxaiDOdbfv1JHXNAln2nbq1IvBOrmP"
file_list = drive.ListFile({'q': f"'{folder}' in parents and trashed=false"}).GetList()
if st.checkbox("Show file list?", True):
for index, file in enumerate(file_list):
st.write(index + 1, file['title'])
file.GetContentFile(path + file['title'])
settings.yaml :
client_config_backend: settings
client_config:
client_id: 556191342382-tbsh3m4jdh21j2jlnjarchkufljbsoec.apps.googleusercontent.com
client_secret: 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
save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.json
get_refresh_token: True
oauth_scope:
- https://www.googleapis.com/auth/drive.file
- https://www.googleapis.com/auth/drive.install
- https://www.googleapis.com/auth/drive
- https://www.googleapis.com/auth/drive.metadata

Upload only new files to google drive leaving already uploaded files using Python?

Here is my code
suggestions with my below code to upload only new files to google drive leaving already uploaded files using Python ??
I want to upload files whenever a new files comes to a folder then to google drive
import os
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
drive = GoogleDrive(gauth)
folder = '1aoonhCebvI5DddvJVGTzBvWs2BPn_yXN'
directory = "/Volumes/g2track/Shared/Egnyte Audit Reports/2022/Abhi"
for f in os.listdir(directory):
filename=os.path.join(directory, f)
gfile = drive.CreateFile({'parents' : [{'id' : folder}],'title' : f})
gfile.SetContentFile(filename )
gfile.Upload()

Pydrive error: No downloadLink/exportLinks for mimetype found in metadata

I am trying to download a simple text file from google drive automatically with the pydrive module for python. I keep getting the following error:
Traceback (most recent call last):
File "C:\GIS\AVGOPS\Scripts\GoogleDrive_Test.py", line 20, in
item.GetContentFile(r'C:\Users\pfilyer\Desktop\googedrive\' + item['title'])
File "C:\Python27\ArcGIS10.4\lib\site-packages\pydrive\files.py", line 210, in GetContentFile
self.FetchContent(mimetype, remove_bom)
File "C:\Python27\ArcGIS10.4\lib\site-packages\pydrive\files.py", line 43, in _decorated
return decoratee(self, *args, **kwargs)
File "C:\Python27\ArcGIS10.4\lib\site-packages\pydrive\files.py", line 265, in FetchContent
'No downloadLink/exportLinks for mimetype found in metadata')
FileNotDownloadableError: No downloadLink/exportLinks for mimetype found in metadata
Any suggestions?
import pydrive
from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
gauth = GoogleAuth()
gauth.LoadCredentialsFile(r"C:\Users\XXXXX\.credentials\drive-python-quickstart.json")
drive = GoogleDrive(gauth)
print "Auth Success"
folder_id = '0BxbuUXtrs7adSFFYMG0zS3VZNFE'
lister = drive.ListFile({'q': "'%s' in parents" % folder_id}).GetList()
for item in lister:
print item['title']
item.GetContentFile(r'C:\Users\XXXXX\Desktop\googedrive\\' + item['title'])
You are possibly trying to download a google document, spreadsheet or whatever else which is not a ordinary file.
I got exactly the same error a few moments ago, when I tried to download a file of mimeType: application/vnd.google-apps.document. The document has to be exported to other format before downloading.
Check this:
import pydrive
from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
gauth = GoogleAuth()
gauth.LoadCredentialsFile(r"C:\Users\XXXXX\.credentials\drive-python- quickstart.json")
drive = GoogleDrive(gauth)
print "Auth Success"
folder_id = '0BxbuUXtrs7adSFFYMG0zS3VZNFE'
lister = drive.ListFile({'q': "'%s' in parents" % folder_id}).GetList()
for item in lister:
print(item['title'])
# this should tell you which mimetype the file you're trying to download
# has.
print('title: %s, mimeType: %s' % (item['title'], item['mimeType']))
mimetypes = {
# Drive Document files as PDF
'application/vnd.google-apps.document': 'application/pdf',
# Drive Sheets files as MS Excel files.
'application/vnd.google-apps.spreadsheet': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
# see https://developers.google.com/drive/v3/web/mime-types
}
download_mimetype = None
if file['mimeType'] in mimetypes:
download_mimetype = mimetypes[file['mimeType']]
file.GetContentFile(file['title'], mimetype=download_mimetype)
item.GetContentFile(r'C:\Users\XXXXX\Desktop\googedrive\\' + item['title'], mimetype=download_mimetype)
else:
item.GetContentFile(r'C:\Users\XXXXX\Desktop\googedrive\\' + item['title'])
This should work.
When you upload documents to google drive, make sure the 'Convert documents to Google docs editor format option is unchecked in google drive settings. This ensures that your uploaded file is in the same format as the one in your local (e.g., .csv, .txt, etc.). For me, this worked.
In my case it was because there was multiple files with the same name and extension but different ID, I removed one and the code works
Built from the examples in this thread, here a script which walks through all subfolders of a gdrive folder and downloads folderstructure and all files within. Takes care of gdrive docs, spreadsheets and presentations. Logs if a file fails :)
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import os
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
MIMETYPES = {
# Drive Document files as MS dox
'application/vnd.google-apps.document': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
# Drive Sheets files as MS Excel files.
'application/vnd.google-apps.spreadsheet': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
# Drive presentation as MS pptx
'application/vnd.google-apps.presentation': 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
# see https://developers.google.com/drive/v3/web/mime-types
}
EXTENSTIONS = {
'application/vnd.google-apps.document': '.docx',
'application/vnd.google-apps.spreadsheet': '.xlsx',
'application/vnd.google-apps.presentation': '.pptx'
}
f = open("failed.txt","w+")
folder_id = '<folder_id_from_browser_address_bar>'
root = 'drive_download'
os.mkdir(root)
def escape_fname(name):
return name.replace('/','_')
def search_folder(folder_id, root):
file_list = drive.ListFile({'q': "'%s' in parents and trashed=false" % folder_id}).GetList()
for file in file_list:
# print('title: %s, id: %s, kind: %s' % (file['title'], file['id'], file['mimeType']))
# print(file)
if file['mimeType'].split('.')[-1] == 'folder':
foldername = escape_fname(file['title'])
create_folder(root,foldername)
search_folder(file['id'], '{}{}/'.format(root,foldername))
else:
download_mimetype = None
filename = escape_fname(file['title'])
filename = '{}{}'.format(root,filename)
try:
print('DOWNLOADING:', filename)
if file['mimeType'] in MIMETYPES:
download_mimetype = MIMETYPES[file['mimeType']]
file.GetContentFile(filename+EXTENSTIONS[file['mimeType']], mimetype=download_mimetype)
else:
file.GetContentFile(filename)
except:
print('FAILED')
f.write(filename+'\n')
def create_folder(path,name):
os.mkdir('{}{}'.format(path,escape_fname(name)))
search_folder(folder_id,root+'/')
f.close()

Python: Copy a file in google drive into a specific folder

I'm making a spreadsheet that I need to reset every single week, I'm trying to use the PyDrive API to make a copy of the file, which works perfectly with the code below.
My problem is that i cant specify which folder I want to save the copy in. I would like to have a folder called "archive" which contains all my backups. Is this possible, using PyDrive and if so, how? Thanks!
## Create a new Document in Google Drive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
folder = "########"
title = "Copy of my other file"
file = "############"
drive.auth.service.files().copy(fileId=file,
body={"parents": [{"kind": "drive#fileLink",
"id": folder}], 'title': title}).execute()
Thanks to the comment from #Rawing I figured it out. It was specified in the "folder" variable

Manage files from public Google Drive URL using PyDrive

I`m using PyDrive QuickStart script to list my Google Drive files.
Code:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
print(file_list)
I'm able to list my files normally, but I need to list and manage files from another public drive URL (which is not the my personal authenticated drive) from my already authenticated GoogleDrive account like if I was using requests lib.
Any ideas how to do it?
You need to get the folder ID. You can find the ID in the URL of the folder. An example would be:
https://drive.google.com/open?id=0B-schRXnDFZeX0t0RnhQVXXXXXX (the part of the URL after the id=).
List contents of a folder based on ID. Given your code you replace file_list = ... with:
file_id = '<Your folder id here.>'
file_list = drive.ListFile({'q': "'%s' in parents and trashed=false" % file_id}).GetList()
If this does not work, you may have to add the remote folder to your Google Drive using the "Add to Drive" button in the top right corner of the shared folder when opened in a browser.
2.1 Creating a file in a folder can be done like so:
file_object = drive.CreateFile({
"parents": [{"kind": "drive#fileLink",
"id": parent_id}],
'title': file_name,
# (Only!) If the new 'file' object is going be a folder:
'mimeType': "application/vnd.google-apps.folder"
})
file_object.Upload()
If this fails check whether you have write permissions to the folder.
2.2 Deleting/Trashing a file can be done with the updated version available from GitHub: pip install instructions, Delete/Trash/UnTrash documentation
Finally, there is a feature request to Upload to folders as described in 2.1, and listing files of a folder, as described in 2. - if you find the above not to work you can add this as an issue / feature request to the repository.

Categories

Resources