Skip to content

Instantly share code, notes, and snippets.

@bennylope
Created June 23, 2020 20:07
Show Gist options
  • Save bennylope/20db53a7f87e507ce1b4ca2391da0f09 to your computer and use it in GitHub Desktop.
Save bennylope/20db53a7f87e507ce1b4ca2391da0f09 to your computer and use it in GitHub Desktop.
import requests
class RemoteFile:
"""
Context manager for handling remote OR local files
Can be used like so:
>>> with RemoteFile("/path/to/local/file.txt") as f:
>>> for line in f:
>>> print(line)
Or like this:
>>> with RemoteFile("http://example.com/path/to/remote/file.txt") as f:
>>> for line in f:
>>> print(line)
"""
def __init__(self, file_path):
"""
Initialize with the file path/URL
Args:
file_path: either a URL or a local path
"""
self.file_path = file_path
def __enter__(self):
"""
Open the file and return content
If this is a local file path it will return the file object.
If it is a URL it will return the unicode text of the response.
"""
if self.is_remote:
response = requests.get(self.file_path)
self.contents = response.text
else:
self.contents = open(self.file_path, mode="r")
return self.contents
def __exit__(self, type, value, traceback):
if self.is_local:
self.contents.close()
@property
def is_remote(self):
return self.file_path.startswith("http")
@property
def is_local(self):
return not self.is_remote
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment