Skip to content

Commit

Permalink
Add new file
Browse files Browse the repository at this point in the history
  • Loading branch information
rajeee committed Dec 22, 2023
1 parent 9d3e03c commit 5d52528
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions buildstock_query/file_getter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import requests
from pathlib import Path
from urllib.parse import urlparse
import io


class OpenOrDownload:
def __init__(self, path_or_url: str):
self.path_or_url = path_or_url
self.file = None
self.is_url = urlparse(path_or_url).scheme in ['http', 'https']

def __enter__(self):
if self.is_url:
# URL: Download the file
response = requests.get(self.path_or_url, stream=True)
response.raise_for_status()
self.file = io.BytesIO(response.content)
else:
# Local Path: Open the file
file_path = Path(self.path_or_url)
if file_path.exists() and file_path.is_file():
self.file = open(file_path, 'r')
else:
raise FileNotFoundError(f"File not found: {self.path_or_url}")
return self.file

def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()

0 comments on commit 5d52528

Please sign in to comment.