pythonrequestfile-management

Getting Error 22 for dynamically naming a downloaded files using request from Python


So I'm trying to automate a daily download in jupyter and trying to name it adding the date and time of the download but I get this error 22:

OSError: [Errno 22] Invalid argument: 'C:\\Users\\Emilio\\Downloads\\BonosMX_2021-09-29_01:26:40_PM.xlsx'

This is what I'm trying:

import requests
from openpyxl import load_workbook
from datetime import datetime
from pathlib import Path

url='www.xyz.com/file.xyz'
r = requests.get(url, allow_redirects=True)
print(r.headers.get('content-type'))
fechaDes = datetime.now().strftime("_%Y-%m-%d_%I:%M:%S_%p")
path = r"C:\Users\Emilio\Downloads\BonosMX" + fechaDes + ".xlsx"
open(path, 'wb').write(r.content)

Thanks for the help!


Solution

  • Windows is quite fussy about what you can put into paths. Try this:

    fechaDes = datetime.now().strftime("_%Y-%m-%d_%I-%M-%S_%p")
    

    In general stick to _ and - as separators... and be aware that windows also has limits on path length which are quite easy to hit.