pythongoogle-sheetsgspread

Gspread: I want to copy a spreadsheet to another folder


I'm trying to copy a spreadsheet to a custom folder but I get the following error message:

gspread.exceptions.APIError: {'code': 404, 'message': 'File not found: <folder_id>', 'errors': [{'message': 'File not found: <folder_id>', 'domain': 'global', 'reason': 'notFound', 'location': 'fileId', 'locationType': 'parameter'}]}

This is my code, and the authentication seems to working correctly:

def copy_spreadsheet(credentials):
    # Authenticate with Google Sheets using the JSON key file
    scope = ['https://www.googleapis.com/auth/spreadsheets',
             "https://www.googleapis.com/auth/drive"]


    creds = Credentials.from_service_account_file(
        credentials, scopes=scope)

    client = gspread.authorize(creds)
  
    client.copy(
        "<sheet_id>",
        title='new',
        copy_permissions=True,
        folder_id='<folder_id>')

Besides, when I copy without a "folder_id" and I do: print(client.list_spreadsheet_files()),

I get a list of the spreadsheets, but they are not on my Google Drive,

Can someone help me?

Thanks in advance!


Solution

  • Modification points:

    From your following script,

    creds = Credentials.from_service_account_file(
            credentials, scopes=scope)
    

    I thought that in your situation, it seems that the service account is used.

    And, from your following situation,

    Besides, when I copy without a "folder_id" and I do: print(client.list_spreadsheet_files()),

    I get a list of the spreadsheets, but they are not on my Google Drive,

    I'm worried that in your current situation, the folder of folder_id might be put into Google Drive of your Google account. If my understanding is correct, the Google Drive of the service account is different from the Google Drive of your Google account. I thought that this might be the reason for your current issue.

    In order to show the copied Spreadsheet in your Google Drive, as a simple method, how about the following flow?

    Flow:

    1. Share the folder of folder_id in your Google Drive with the email of the service account.

      • In this case, please manually operate this using your browser in your Google Drive.
      • You can confirm the email of the service account in the file of credentials.
    2. Run your showing script.

    By this flow, you can see the copied Spreadsheet in the folder of folder_id on your Google Drive.

    Note: