Search code examples
python-3.xgoogle-apipygsheets

Date as part of file name nming convention for Gsheet API exported xlsx file using python


May I know what function I need to add/replace on my python script, here's my issue I have exported xlsx file from gsheet API to my server and I need to add an generic filename with file name and date (ex. FILENAME20211107.xlsx)

here's my code:

  with open("/xlsx/FILENAME.xlsx", 'wb') as f:
    f.write(res.content)

Solution

  • From the goal is to set File naming convention using date in the script for example. If I run the script the extracted file from google api will be automatically named like this format "filename_202111107.xlsx", you want to use the specific filename like filename_202111107.xlsx in your script. In this case, how about the following modification?

    Modified script:

    import datetime # Please add this.
    import os # Please add this.
    
    path = "/xlsx/"
    prefix = "sampelName"
    suffix = datetime.datetime.now().strftime("%Y%m%d")
    filename = prefix + "_" + suffix + ".xlsx"
    v = os.path.join(path, filename)
    print(v) # <--- /xlsx/sampelName_20211108.xlsx
    
    with open(v, 'wb') as f:
      f.write(res.content)
    

    When above script is run, v is /xlsx/sampelName_20211108.xlsx.

    Note:

    • In your comment, you use 202111107 of filename_202111107.xlsx. In this case, when the script is run on November 7, 2021, you want to use 20211107. I understood like this. In your question, I understood that you might want to use 20211107 instead of 202111107.