Techniquecore
Process a large text file as a stream
Also called stream a file, read a large file line by line, process a file larger than memory, streaming text processing, constant-memory file processing.
Read a text file one line at a time and keep only the state that the result needs, so that the memory of the program does not grow with the size of the file.
Purpose
A program that reads a whole file into memory needs memory for the whole file, and often for more than that: a list of lines holds one object for each line. When the file is larger than the memory, the program fails. When the file is only large, the program is slow to start, because it does no work until the read ends.
Many results do not need the whole file. A line count, a sum, a maximum, a filter or a word count needs one line at a time and a small state. The technique reads the file as a stream: it reads one line, updates the state, and then forgets the line. The memory of the program then depends on the length of the longest line and on the size of the state, not on the size of the file. The Python tutorial says about a loop over a file: "This is memory efficient, fast, and leads to simple code".1
Steps
- Open the file with a buffered reader. The reader reads large blocks from the file and gives the program one line at a time. Rust says: "reading line-by-line is inefficient without using a buffer".2
- Read one line in each iteration of a loop. Use the line reader of the language, not a call that returns all the lines. Decide what a line is: whether the LF stays in the line, and what to do with a CR before it (see Line ending).
- Keep only the state that the result needs. Keep a count, a sum, a maximum, or a map of counts. Do not add each line to a list. If a line must stay after the next read, copy it, because some readers use the same buffer again for the next line.
- Write each output line as soon as it is ready, through a buffered writer. Then the output also does not wait for the end of the input.
- Check for an error after the loop. Some readers stop the loop on an error and on the end of the file in the same way, and keep the error for a separate call.
- Close the file, also when the loop ends early with an error. Use the scope construct of the language:
with,trywith resources,defer, or a value that closes the file when it goes out of scope.
Example
In Python. The program writes a file of 200000 lines with the numbers 0 to 999, and then gets the number of lines, their sum and their maximum in two ways. read_all reads the whole file and makes a list. stream reads one line at a time and keeps three numbers. tracemalloc.get_traced_memory gives "the current size and peak size of memory blocks traced by the tracemalloc module".3 The two functions give the same result. The peak memory of read_all is more than 5 times the size of the file, and the peak memory of stream is less than a tenth of it:
import os
import tempfile
import tracemalloc
directory = tempfile.mkdtemp()
path = os.path.join(directory, 'numbers.txt')
with open(path, 'w', encoding='utf-8') as f:
for i in range(200_000):
f.write(f'{i % 1000}\n')
size = os.path.getsize(path)
print('file size:', size, 'bytes')
def read_all(path):
with open(path, encoding='utf-8') as f:
numbers = [int(line) for line in f.read().splitlines()]
return len(numbers), sum(numbers), max(numbers)
def stream(path):
count = total = 0
largest = None
with open(path, encoding='utf-8') as f:
for line in f: # one line at a time
n = int(line)
count += 1
total += n
largest = n if largest is None else max(largest, n)
return count, total, largest
for function in (read_all, stream):
tracemalloc.start()
result = function(path)
peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
print(f'{function.__name__}: {result}, peak above 5 times the file size: {peak > 5 * size}, peak below 1/10 of the file size: {peak < size / 10}')
os.remove(path)
os.rmdir(directory)
file size: 778000 bytes
read_all: (200000, 99900000, 999), peak above 5 times the file size: True, peak below 1/10 of the file size: False
stream: (200000, 99900000, 999), peak above 5 times the file size: False, peak below 1/10 of the file size: True
The example files do the same in Go, Rust, JavaScript, Java, C and Bash. Each file writes the same file of numbers, and reads it again one line at a time.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.IntSummaryStatistics;
import java.util.stream.Stream;
public class Main {
static IntSummaryStatistics stream(Path path) throws IOException {
// Files.lines reads the lines as the stream needs them. The try closes the file.
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
return lines.mapToInt(Integer::parseInt).summaryStatistics();
}
}
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("stream");
Path path = dir.resolve("numbers.txt");
try (BufferedWriter w = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
for (int i = 0; i < 1_000_000; i++) {
w.write(Integer.toString(i % 1000));
w.write('\n');
}
}
IntSummaryStatistics s = stream(path);
System.out.println("lines: " + s.getCount() + " sum: " + s.getSum() + " max: " + s.getMax());
Files.delete(path);
Files.delete(dir);
}
}
lines: 1000000 sum: 499500000 max: 999
Files.lines returns a Stream<String> that reads the lines as the stream needs them, and summaryStatistics keeps the count, the sum and the maximum. The try with resources closes the stream, and so the file.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static int stream(const char *path, long *count, long long *total, long *largest) {
FILE *f = fopen(path, "r");
if (f == NULL) {
return -1;
}
char *line = NULL; // getline makes the buffer larger when a line needs it
size_t cap = 0;
*count = 0, *total = 0, *largest = 0;
while (getline(&line, &cap, f) != -1) {
long n = strtol(line, NULL, 10);
if (*count == 0 || n > *largest) {
*largest = n;
}
++*count;
*total += n;
}
int failed = ferror(f);
free(line);
fclose(f);
return failed ? -1 : 0;
}
int main(void) {
char dir[] = "/tmp/streamXXXXXX";
if (mkdtemp(dir) == NULL) {
return 1;
}
char path[64];
snprintf(path, sizeof path, "%s/numbers.txt", dir);
FILE *f = fopen(path, "w");
if (f == NULL) {
return 1;
}
for (int i = 0; i < 1000000; i++) {
fprintf(f, "%d\n", i % 1000);
}
if (fclose(f) != 0) {
return 1;
}
long count, largest;
long long total;
int rc = stream(path, &count, &total, &largest);
printf("lines: %ld sum: %lld max: %ld rc: %d\n", count, total, largest, rc);
remove(path);
rmdir(dir);
return rc != 0;
}
lines: 1000000 sum: 499500000 max: 999 rc: 0
getline reads one line into a buffer that it makes larger when a line needs it, and the program frees the buffer once, after the loop. ferror after the loop shows whether the loop stopped on an error and not at the end of the file.
import { createReadStream, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createInterface } from "node:readline";
async function stream(path) {
const lines = createInterface({ input: createReadStream(path), crlfDelay: Infinity });
let count = 0, total = 0, largest;
for await (const line of lines) { // one line at a time, with no LF
const n = Number(line);
count++;
total += n;
largest = largest === undefined ? n : Math.max(largest, n);
}
return { count, total, largest };
}
const dir = mkdtempSync(join(tmpdir(), "stream-"));
try {
const path = join(dir, "numbers.txt");
const parts = [];
for (let i = 0; i < 1_000_000; i++) parts.push(`${i % 1000}\n`);
writeFileSync(path, parts.join(""));
console.log(await stream(path));
} finally {
rmSync(dir, { recursive: true });
}
{ count: 1000000, total: 499500000, largest: 999 }
readline.createInterface reads a stream from createReadStream and gives one line at a time, with no LF, to for await. With crlfDelay: Infinity, a CR and an LF are one end of line. The file of numbers is written with one call, so this example needs memory for the whole file when it writes it, but not when it reads it.
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strconv"
)
func stream(path string) (count, total, largest int, err error) {
f, err := os.Open(path)
if err != nil {
return 0, 0, 0, err
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() { // one line at a time, with no LF
n, err := strconv.Atoi(sc.Text())
if err != nil {
return 0, 0, 0, err
}
if count == 0 || n > largest {
largest = n
}
count++
total += n
}
return count, total, largest, sc.Err()
}
func main() {
dir, err := os.MkdirTemp("", "stream")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "numbers.txt")
f, err := os.Create(path)
if err != nil {
panic(err)
}
w := bufio.NewWriter(f)
for i := range 1_000_000 {
fmt.Fprintf(w, "%d\n", i%1000)
}
if err := w.Flush(); err != nil {
panic(err)
}
f.Close()
count, total, largest, err := stream(path)
fmt.Println("lines:", count, "sum:", total, "max:", largest, "error:", err)
}
lines: 1000000 sum: 499500000 max: 999 error: <nil>
bufio.NewScanner reads the file in blocks and gives one line at a time, with no LF, through Text. The loop keeps three numbers, and sc.Err() after the loop shows whether the scan stopped on an error. A bufio.Writer writes the file, and Flush writes the last block.
use std::fs::{self, File};
use std::io::{self, BufRead, BufReader, BufWriter, Write};
fn stream(path: &std::path::Path) -> io::Result<(u64, u64, Option<u64>)> {
let mut reader = BufReader::new(File::open(path)?);
let mut line = String::new();
let (mut count, mut total, mut largest) = (0, 0, None);
loop {
line.clear(); // read_line appends to the buffer
if reader.read_line(&mut line)? == 0 {
break;
}
let n: u64 = line.trim_end().parse().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
count += 1;
total += n;
largest = largest.max(Some(n));
}
Ok((count, total, largest))
}
fn main() -> io::Result<()> {
let dir = std::env::temp_dir().join(format!("stream-{}", std::process::id()));
fs::create_dir(&dir)?;
let path = dir.join("numbers.txt");
let mut w = BufWriter::new(File::create(&path)?);
for i in 0..1_000_000 {
writeln!(w, "{}", i % 1000)?;
}
w.flush()?;
drop(w);
let (count, total, largest) = stream(&path)?;
println!("lines: {count} sum: {total} max: {largest:?}");
fs::remove_dir_all(&dir)
}
lines: 1000000 sum: 499500000 max: Some(999)
BufReader reads the file in blocks, and read_line adds the next line to one String. The loop clears the string before each read, so it holds one line at a time. read_line returns 0 at the end of the file.
dir=$(mktemp -d)
seq 0 999999 | awk '{ print $1 % 1000 }' > "$dir/numbers.txt"
# awk reads one line at a time, and keeps only the count, the sum and the maximum.
awk 'NR == 1 || $1 > max { max = $1 } { sum += $1 } END { print "lines:", NR, "sum:", sum, "max:", max }' "$dir/numbers.txt"
rm -rf "${dir:?}"
lines: 1000000 sum: 499500000 max: 999
awk reads one record at a time, and a record is a line. The variables max and sum are the state, and the END action prints the result.
When to use
Use the technique when the result of each line depends only on the line and a small state: count, sum, filter, convert, extract fields, check a format, or count the words in a map. Use it also when the input does not end, as a pipe or a log file that grows (see Follow a growing file), and when the program must give the first output early.
Do not use it when the program needs all the lines at the same time. A sort needs all the lines before it can write the first line. For a file larger than the memory, a sort program writes sorted parts to temporary files and then merges them. GNU sort has the option -S to "Use a main-memory sort buffer of the given size", and it puts its temporary files in the directory of the variable TMPDIR or of the option -T.4 A stream also does not help when the state itself grows with the file. A map of the distinct lines of a file in which most lines are different has almost the size of the file. For a small file, reading the whole file is simpler, and it is correct.
Pitfalls
- A call that reads all the lines.
f.readlines()in Python,Files.readAllLinesin Java andFile.ReadAllLinesin .NET return all the lines at once. Java says ofreadAllLines: "It is not intended for reading in large files."5 .NET says: "when you are working with very large files, ReadLines can be more efficient."6 Use the call that returns the lines one at a time: a loop over the file in Python,Files.linesin Java,File.ReadLinesin .NET. - A line that is too long for the reader. Go
bufio.Scannerhas a maximum line length.MaxScanTokenSizeis64 * 1024, and a longer line stops the scan withErrTooLong.7 The scan then ends early, and only a check ofErrshows that the loop did not read the whole file. CallBufferwith a larger maximum, or usebufio.Reader. Go says: "Programs that need more control over error handling or large tokens, or must run sequential scans on a reader, should use bufio.Reader instead."7 In the block, the first scanner has the default maximum, and the second scanner has a maximum of 1 MiB:
package main
import (
"bufio"
"fmt"
"strings"
)
func count(sc *bufio.Scanner) {
n := 0
for sc.Scan() {
n++
}
fmt.Println("lines:", n, "error:", sc.Err())
}
func main() {
text := "short\n" + strings.Repeat("x", 100*1024) + "\nlast\n" // a line of 100 KiB
count(bufio.NewScanner(strings.NewReader(text)))
sc := bufio.NewScanner(strings.NewReader(text))
sc.Buffer(make([]byte, 0, 64*1024), 1024*1024) // allow lines up to 1 MiB
count(sc)
}
lines: 1 error: bufio.Scanner: token too long
lines: 3 error: <nil>
- A line with no limit. A reader with no maximum line length needs memory for the longest line. A file with no LF is one line, so a stream reads all of it into memory. Rust says of
read_line: "it is possible for an attacker to continuously send bytes without ever sending a newline or EOF".2 For input that the program does not trust, limit the length of a line, for example withtakein Rust or with the maximum ofScanner.Bufferin Go. - A line buffer that is not cleared. Rust
read_lineadds to the string: "Previous content of the buffer will be preserved. To avoid appending to the buffer, you need to clear it first."2 A loop that does not clear the string gets all the lines before it again, and the memory grows with the file:
use std::io::{BufRead, Cursor};
fn main() {
let text = "one\ntwo\nthree\n";
let mut reader = Cursor::new(text);
let mut line = String::new();
while reader.read_line(&mut line).unwrap() > 0 {
println!("no clear: {:?}", line); // the old lines stay in the buffer
}
let mut reader = Cursor::new(text);
let mut line = String::new();
loop {
line.clear();
if reader.read_line(&mut line).unwrap() == 0 {
break;
}
println!("clear: {:?}", line);
}
}
no clear: "one\n"
no clear: "one\ntwo\n"
no clear: "one\ntwo\nthree\n"
clear: "one\n"
clear: "two\n"
clear: "three\n"
- A buffer that the next read changes. Go
Scanner.Bytessays: "The underlying array may point to data that will be overwritten by a subsequent call to Scan."7 Cgetlineuses one buffer for all the lines, and it can move the buffer when a line needs more space.8 Copy the line if the program keeps it after the next read. - A file that is not closed. Java
Files.lineskeeps the file open until the stream closes: "The file is closed by closing the stream."5 Use it in atrywith resources. - A CR at the end of each line. Line readers do different things with a CR before an LF. In Go, the end of a line for
bufio.Scanner"is one optional carriage return followed by one mandatory newline", so the CR goes.7 Rustread_lineand Cgetlinestop at the LF and keep all the bytes before it, so the CR stays.28 In Node.js,readlinetakes a CR and an LF as one end of line only when they come close together in time. WithcrlfDelayset toInfinity, "\r followed by \n will always be considered a single newline".9 Test the reader with a file that has CRLF line endings. - A character split between two blocks. A code that reads fixed blocks and decodes each block can cut a UTF-8 character in two. Split the bytes at each LF first, and decode each line after, as the line readers of the languages do.
Tools that do it
| Language | Read one line at a time | Reads all the lines at once |
|---|---|---|
| Python | for line in f |
f.readlines(), f.read().splitlines() |
| Go | bufio.Scanner, bufio.Reader.ReadString |
os.ReadFile and strings.Split |
| Rust | BufRead::read_line, BufRead::lines |
fs::read_to_string |
| JavaScript (Node.js) | readline.createInterface with for await |
fs.readFileSync and split |
| Java | Files.lines, BufferedReader.readLine |
Files.readAllLines |
| C# | File.ReadLines, StreamReader.ReadLine |
File.ReadAllLines |
| C (POSIX) | getline, fgets |
fread of the whole file |
| Shell | awk, sed, grep, while read |
none |
POSIX getline reads "until it encounters a character matching the delimiter character", and makes the buffer larger when a line needs more space.8 The Node.js readline module reads data from a stream "one line at a time".9 In awk, "Input shall be interpreted as a sequence of records. By default, a record is a line".10 So an awk program is a stream in which the state is in variables and the END action writes the result.
References
- The Python Tutorial, Input and Output, 7.2.1 Methods of File Objects
- The Rust Standard Library, std::io::BufRead, read_line; read_until
- The Python Standard Library, tracemalloc, Trace memory allocations, get_traced_memory
- GNU Coreutils manual, sort invocation, -S, --buffer-size; -T, --temporary-directory
- Java SE 25 API, java.nio.file.Files, lines(Path, Charset); readAllLines(Path, Charset); readAllBytes
- .NET API reference, File.ReadLines Method, Remarks
- Go standard library, package bufio, MaxScanTokenSize; ErrTooLong; type Scanner; func (*Scanner) Buffer
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), getdelim, getline, DESCRIPTION
- Node.js documentation, Readline, readline.createInterface (crlfDelay); Example, Read file stream line-by-Line
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), awk, DESCRIPTION
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag PKH23E Edit this page History Report an error Markdown