Get list of files and folders in Google Drive storage using Python
Last Updated :
01 Oct, 2020
In this article, we are going to have a look at how can we get a list of files (or folders) stored in our Google Drive cloud storage using Google Drive API in Python. It is a REST API that allows you to leverage Google Drive storage from within your app or program.
So, let's create a simple Python script that communicates with Google Drive API.
Requirements:
- Python (2.6 or higher)
- A Google account with Google Drive enabled
- Google API client and Google OAuth libraries
Installation:
Install the required libraries by running this command:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
Now, follow these steps to set up your Google account to work with Google Drive API.
Create a new project
Go to APIs and Services- Enable Google Drive API for this project.
Enable API
Enable Google Drive API- Go to the OAuth Consent screen and configure the Consent screen for your project.
Go to OAuth Consent screen
Select External and click on Create- Enter the name of your application. It will be shown on the consent screen.
Enter the application name and select email address
Go to Credentials- Click on Create credentials, and go to OAuth Client ID.
Click on Create Credentials and select OAuth Client ID- Enter your application's name, and click Create.
Enter the Application Name and click on Create- Your Client ID will be created. Download it to your computer and save it as credentials.json
Download json file
NOTE: Do not share your CLIENT ID or CLIENT SECRETS with anyone.
Now, we are done with the setup and installation. So, let's write the python script:
Python3
# import the required libraries
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# Define the SCOPES. If modifying it,
# delete the token.pickle file.
SCOPES = ['https://www.googleapis.com/auth/drive']
# Create a function getFileList with
# parameter N which is the length of
# the list of files.
def getFileList(N):
# Variable creds will store the user access token.
# If no valid token found, we will create one.
creds = None
# The file token.pickle stores the
# user's access and refresh tokens. It is
# created automatically when the authorization
# flow completes for the first time.
# Check if file token.pickle exists
if os.path.exists('token.pickle'):
# Read the token from the file and
# store it in the variable creds
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If no valid credentials are available,
# request the user to log in.
if not creds or not creds.valid:
# If token is expired, it will be refreshed,
# else, we will request a new one.
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the access token in token.pickle
# file for future usage
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
# Connect to the API service
service = build('drive', 'v3', credentials=creds)
# request a list of first N files or
# folders with name and id from the API.
resource = service.files()
result = resource.list(pageSize=N, fields="files(id, name)").execute()
# return the result dictionary containing
# the information about the files
return result
# Get list of first 5 files or
# folders from our Google Drive Storage
result_dict = getFileList(5)
# Extract the list from the dictionary
file_list = result_dict.get('files')
# Print every file's name
for file in file_list:
print(file['name'])
Now, run the script:
python3 script.py
This will attempt to open a new window in your default browser. If this fails, copy the URL from the console and manually open it in your browser.
Now, Log in to your Google account if you aren't already logged in. If there are multiple accounts, you will be asked to choose one of them. Then, click on the Allow button.
After the authentication has been completed, your browser will display a message saying The authentication flow has been completed. You may close this window.
Once the authentication has been completed, this will print the names of first N files (or folders) in your Google Drive storage.
Note: The file credentials.json should be in the same directory as the Python script. If not so, you have to specify the full path to the file in the program.
Similar Reads
Upload and Download files from Google Drive storage using Python In this article, we are going to see how can we download files from our Google Drive to our PC and upload files from our PC to Google Drive using its API in Python. It is a REST API that allows you to leverage Google Drive storage from within your app or program. So, let's go ahead and write a Pytho
6 min read
How to create a list of files, folders, and subfolders in Excel using Python ? In this article, we will learn How to create a list of Files, Folders, and Sub Folders and then export them to Excel using Python. We will create a list of names and paths using a few folder traversing methods explained below and store them in an Excel sheet by either using openpyxl or pandas module
12 min read
How to List all Files and Directories in FTP Server using Python? FTP ( File Transfer Protocol ) is set of rules that computer follows to transfer files across computer network. It is TCP/IP based protocol. FTP lets clients share files. FTP is less secure because of files are shared as plain text without any encryption across the network. It is possible using pyt
2 min read
Uploading files on Google Drive using Python In the modern era of the internet, a large number of mundane or work-related tasks are carried out over the internet. Compromise of data stored on a device could cause massive harm to an individual/company. Considering the rise in the number of malware, viruses, worms, trojan horse etc the security
3 min read
Python - Get list of files in directory with size In this article, we are going to see how to extract the list of files of the directory along with its size. For this, we will use the OS module. OS module in Python provides functions for interacting with the operating system. OS comes under Pythonâs standard utility modules. This module provides a
9 min read