Created
March 28, 2025 16:49
-
-
Save do-me/4e3d495d887b9abe948e8a43fac63e39 to your computer and use it in GitHub Desktop.
Save and load python dict as gzipped json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json, gzip | |
def load_json(file_path): | |
try: | |
with gzip.open(file_path, 'rt', encoding='utf-8') as f: | |
return json.load(f) | |
except OSError: #if the file is not gzipped | |
with open(file_path, 'r', encoding='utf-8') as f: | |
return json.load(f) | |
def save_json(data, file_path, compress=True): | |
if compress: | |
with gzip.open(file_path, 'wt', encoding='utf-8') as f: | |
json.dump(data, f) # Use indent for readability (optional) | |
else: | |
with open(file_path, 'w', encoding='utf-8') as f: | |
json.dump(data, f) | |
save_json(zip_codes, "zip_codes.json.gz", compress=True) | |
zip_codes = load_json("zip_codes.json.gz") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment