Search code examples
pythongoogle-apigoogle-drive-apigoogle-api-python-client

Search for files with ' in them with the Google Drive Python API


I'm using this code to find a file in My Drive with the Google Drive Python API:

results = service.files().list(q="name='"+finalfile+"'" fields="files(id)").execute()`

However, I get an error 400 whenever the file name has " ' " in it (I guess that it messes up the request). How can I search for a file with the apostrophe in it without crashing the program?


Solution

  • When your script is run, an error like invalid syntax occurs, because of no , between q="name='"+finalfile+"'" and fields="files(id)". But in your question, you say I get an error 400 whenever the file name has " ' " in it. From this situation, I guessed that you might have miscopied your script.

    About your error of I get an error 400 whenever the file name has " ' " in it, in your situation, please escape ' like name='sample\'sample' and test it again. I thought that the reason for your current error might be due to this. In the case of your script, how about the following modification?

    Modified script:

    results = service.files().list(q="name='" + finalfile.replace("'", "\\'") + "'", fields="files(id)").execute()
    
    • By this modification, when the value of finalfile is sample'sample, this file can be retrieved.

    Reference: