How to Stream a Large JSONL File Line by Line in Python
Process a large JSON-lines file incrementally using streaming techniques to avoid loading the entire file into memory.
Python code
42 linesimport json
def process_large_file(filepath, chunk_size=8192):
"""
Stream a large JSON-lines file line by line, processing each record
without loading the entire file into memory.
"""
total_count = 0
total_sum = 0
with open(filepath, 'r') as f:
while True:
chunk = f.readlines(chunk_size)
if not chunk:
break
for line in chunk:
line = line.strip()
if not line:
continue
record = json.loads(line)
total_count += 1
total_sum += record.get('value', 0)
return total_count, total_sum
if __name__ == "__main__":
# Simulate a large file with a generator to demonstrate streaming
import tempfile
import os
# Create a sample large file (1000 records)
with tempfile.NamedTemporaryFile(mode='w', suffix='.jsonl', delete=False) as f:
for i in range(1000):
f.write(json.dumps({"id": i, "value": i * 2}) + "\n")
filepath = f.name
# Process it in streaming fashion
count, total = process_large_file(filepath)
print(f"Processed {count} records, total sum: {total}")
# Clean up
os.unlink(filepath)
Output
Processed 1000 records, total sum: 999000
How it works
The function uses readlines(chunk_size) to read a fixed number of lines per chunk, balancing memory usage and I/O efficiency. Each line is parsed with json.loads and processed immediately, so only one record stays in memory at a time. The strip() call removes trailing newlines, and empty lines are skipped to avoid parsing errors. This pattern is ideal for files too large to fit in RAM, as it processes records incrementally.
Common mistakes
- Using `read()` or `readlines()` without size, which loads the whole file into memory
- Forgetting to strip newline characters before JSON parsing
- Assuming all lines are valid JSON; add error handling for corrupted records
Variations
- Use `for line in file:` to iterate directly — simplest, though chunking gives more control over I/O sizes
- Process with a generator that yields each parsed record for downstream pipeline stages
Real-world use cases
- Aggregating metrics from a multi-gigabyte server access log in JSONL format
- Feeding millions of event records into a stream processor like Kafka or a database batch insert
- Filtering and enriching large exported datasets before loading into a data warehouse
Sponsored
More from Data pipelines & processing
- Add a UUID Surrogate Key to Each Row in a CSV with Python easy
- Attach Source File Metadata to Records in Python easy
- Build a Python Utility That Detects Duplicate Records Across Multiple Excel Sheets medium
- Check Null Rate Threshold in PySpark DataFrame medium
- Count Records Processed per Category in Python easy
- Create Data Helper Functions in Python for Beginners easy
Keep learning
Related tutorials and quizzes for this topic.