Search code examples
pythongoogle-docs-api

How to save Python API request to .txt file


I'm using Google Docs Python API,specifically the official example Extract text from a document Everything runs fine, at the end I get the extracted text printed to terminal, resulted from the last bit of code, main func

def main():
    """Uses the Docs API to print out the text of a document."""
    credentials = get_credentials()
    http = credentials.authorize(Http())
    docs_service = discovery.build(
        'docs', 'v1', http=http, discoveryServiceUrl=DISCOVERY_DOC)
    doc = docs_service.documents().get(documentId=DOCUMENT_ID).execute()
    doc_content = doc.get('body').get('content')
print(read_strucutural_elements(doc_content))

The thing is Im having trouble trying to save that text to a .txt file, getting this error message

f.write(read_strucutural_elements(doc_content)) UnicodeEncodeError: 'ascii' codec can't encode character u'\xfa' in position 64: ordinal not in range(128)

The return type of the read_structural_elements call and is

print(type(read_strucutural_elements(doc_content)))

<type 'unicode'>

Any suggestion ?

Cheers!


Solution

  • If you are running the script from the terminal, all you have to do is direct it to write the output to a file using the > operator. Something like this:

    python script.py > outfile.txt
    

    This will take whatever output is being printed in the terminal and dump it into the specified file instead.