Home > Back-end >  How to check if google sheet exist? Python
How to check if google sheet exist? Python

Time:07-16

    """
BEFORE RUNNING:
---------------
1. If not already done, enable the Google Sheets API
   and check the quota for your project at
   https://console.developers.google.com/apis/api/sheets
2. Install the Python client library for Google APIs by running
   `pip install --upgrade google-api-python-client`
"""

# TODO: Change placeholder below to generate authentication credentials. See
# https://developers.google.com/sheets/quickstart/python#step_3_set_up_the_sample
#
# Authorize using one of the following scopes:
#     'https://www.googleapis.com/auth/drive'
#     'https://www.googleapis.com/auth/drive.file'
#     'https://www.googleapis.com/auth/spreadsheets'
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = None
if os.path.exists('google.json'):
    creds = Credentials.from_authorized_user_file('google.json', SCOPES)

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(
            'CLIENT.json',SCOPES)
        creds = flow.run_local_server(port=0)
    with open('google.json', 'w') as token:
        token.write(creds.to_json())
service = discovery.build('sheets', 'v4', credentials=creds)

spreadsheet_body = {

    'sheets': [{
        'properties': {
            'title': str(files[0])
        }
    }]

}
request = service.spreadsheets().create(body=spreadsheet_body)
if request == str(files[0]):
   pass
else:
    response = request.execute()
    pprint(response)

How can I create condition? if google sheet name exist if TRUE then don't proceed to create. I read the documentation and I didn't see any possible answer or I am just mistaken to understand the documentation please help thank you.

CodePudding user response:

I believe your goal is as follows.

  • You want to check whether a file (Google Spreadsheet) is existing in Google Drive using a filename.
  • You want to achieve this using googleapis for python.

In this case, how about the following sample script? In this case, in order to search the file using the filename, Drive API is used.

Sample script:

filename = str(files[0])

service = build("drive", "v3", credentials=creds)
results = service.files().list(pageSize=1, fields="files(id, name)", q="name='"   filename   "' and mimeType='application/vnd.google-apps.spreadsheet' and trashed=false",).execute()
files = results.get("files", [])

if not files:
    # When the file of filename is not found, this script is run.

    print("No files were found.")

else:
    # When the file of filename is found, this script is run.

    print("Files were found.")

  • When this script is run, you can check whether the file is existing in Google Drive in the filename.

  • In this case, please add a scope of "https://www.googleapis.com/auth/drive.metadata.readonly" as follows. And, please reauthorize the scopes. So, please remove the file of google.json and run the script again.

      SCOPES = [
          "https://www.googleapis.com/auth/spreadsheets",
          "https://www.googleapis.com/auth/drive.metadata.readonly",
      ]
    
  • From your question, I couldn't know whether you are trying to use the script in the shared Drive. So, in this modification, the script cannot be used for the shared Drive. But, if you want to use this script in the shared Drive, please include corpora="allDrives", includeItemsFromAllDrives=True, supportsAllDrives=True to the request.

Reference:

  • Related