pylegs.io.download_file#
- download_file(url: str, save_path: str | Path | BytesIO = None, query: Dict[str, Any] = None, overwrite: bool = False, http_client: Session = None, extract: bool = False, timeout: int | float = None) bytes | None[source]#
Download a file from a URL and save it to a specified path.
- Parameters:
- url
str The URL from which to download the file.
- save_path
PathOrFile The path where the downloaded file will be saved. This can be a string or a
pathlib.Pathobject.- query
Dict[str,Any], optional A dictionary of query parameters to include in the request. Defaults to
None.- overwritebool, optional
If True, overwrite the existing file at
save_path. Defaults toFalse.- http_client
requests.Session, optional The HTTP client to use for making the request. If None, the
requestslibrary is used. Defaults toNone.- extractbool, optional
If
True, decompress the downloaded file if it is inbz2format. Defaults toFalse.
- url
- Returns:
- Raises:
ExceptionIf the HTTP request fails or if there is an error in writing the file.
Notes
If
overwriteisFalseand the file already exists atsave_path, the function returnsNonewithout downloading the file.If
extractisTrue, the function assumes the file is compressed with bz2 and decompresses it before saving.
Examples
>>> download_file('http://example.com/file.txt', 'file.txt') b'file content'
>>> download_file('http://example.com/file.bz2', 'file.txt', extract=True) b'decompressed content'