Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Quickstart

This page shows how to read a file line by line, track progress, and save your position

Rust

use preader::{Config, PReader};

fn main() -> preader::Result<()> {
    let config = Config {
        state_dir: "/tmp/states".into(),
        ..Config::default()
    };

    let reader = PReader::from(config);
    let mut lines = reader.lines("data.txt").state("job-1").build()?;

    while let Some(line) = lines.next() {
        let line = line?;

        println!("{line}, {:.1}% done", lines.percent());
    }

    let state = lines.save()?;

    println!("saved at byte {}", state.position);

    Ok(())
}

Python

from preader import Config, PReader

config = Config(state_dir="/tmp/states")
reader = PReader(config=config)

for line in (lines := reader.lines("data.txt", state="job-1")):
    print(f"{line}, {lines.percent():.1f}% done")

print(f"saved at byte {(state := lines.save()).position}")

What Happens Here

  1. You create a Config that tells preader where to store state files. The remaining fields keep their defaults
  2. You create a PReader from that config
  3. You open a line iterator on data.txt with the state name "job-1". If a saved state with that name exists, the iterator resumes from the saved position. Otherwise it starts from the beginning
  4. You iterate through lines, checking percent() after each one
  5. You call save() to persist the final position to disk

Resuming

The next time you run the same code, the iterator picks up from the saved position:

Rust

// Second run, resumes from where "job-1" left off
let mut lines = reader.lines("data.txt").state("job-1").build()?;

while let Some(line) = lines.next() {
    let line = line?;

    println!("resumed: {line}");
}

Python

# Second run, resumes from where "job-1" left off
for line in reader.lines("data.txt", state="job-1"):
    print(f"resumed: {line}")

If you call save() during iteration, the item being processed is not included in the saved position and will be delivered again on resume. See Saving and Resuming for details

Managing States

Every PReader has a state registry for listing, loading, and deleting saved states. Access it with reader.states() in Rust or reader.states in Python

Rust

let registry = reader.states();

for name in registry.names()? {
    let name = name?;
    let state = registry.load(&name)?;

    println!("{name}: byte {}", state.position);
}

registry.delete("job-1")?;

Python

registry = reader.states

for name in registry.names():
    state = registry.load(name)

    print(f"{name}: byte {state.position}")

registry.delete("job-1")

See State Registry for the full API including search(), find(), exists(), clear(), and more