Lines
The line iterator reads a file as UTF-8 text, yielding one line at a time. In Rust it yields Result<String>; in Python it yields str
Basic Usage
Rust
use preader::PReader;
let reader = PReader::default();
let lines = reader.lines("data.txt").build()?;
for line in lines {
println!("{}", line?);
}
Python
from preader import PReader
reader = PReader()
for line in reader.lines("data.txt"):
print(line)
Lines are split on
\nonly. A bare\ris not treated as a line separator. A\r\nsequence is treated as a single line ending
Invalid UTF-8 bytes cause a
Utf8error in Rust and aValueErrorin Python. The iterator does not silently skip invalid data
Options
| Option | Rust Builder Method | Python Keyword |
|---|---|---|
| Keep line endings | keepends(true) | keepends=True |
| Skip empty lines | skip_empty(true) | skip_empty=True |
| Align start | align(true) | align_start=True |
Keeping Line Endings
By default, line terminators are stripped from the yielded strings. Set keepends to preserve them
Given a file containing "hello\nworld\n":
- Without
keepends: yields"hello","world" - With
keepends: yields"hello\n","world\n"
Rust
let lines = reader.lines("data.txt").keepends(true).build()?;
for line in lines {
let line = line?;
// line includes the trailing \n or \r\n
print!("{line}");
}
Python
for line in reader.lines("data.txt", keepends=True):
# line includes the trailing \n or \r\n
print(line, end="")
Skipping Empty Lines
When skip_empty is enabled, lines that are empty after stripping the terminator are not yielded
Given a file containing "line-0\n\nline-2\n":
- Without
skip_empty: yields"line-0","","line-2" - With
skip_empty: yields"line-0","line-2"
Rust
let lines = reader.lines("data.txt")
.skip_empty(true)
.build()?
.collect::<preader::Result<Vec<_>>>()?;
// ["line-0", "line-2"]
Python
lines = list(reader.lines("data.txt", skip_empty=True))
# ["line-0", "line-2"]
Empty lines still count toward the
skipoption but not towardlimit. If you setskip(1)andskip_empty(true)on a file starting with a blank line, the blank line is counted as the skipped item even though it would not have been yielded
Aligning the Start
When you set a start byte offset that lands in the middle of a line, align (Rust) / align_start (Python) skips the partial first line and begins reading at the next complete line
Given a file containing "abcd\nefgh\n" and start set to 2 (which lands on c inside "abcd"):
- Without
align: yields"cd","efgh" - With
align: yields"efgh"
Rust
let lines = reader.lines("data.txt")
.start(2)
.align(true)
.build()?;
Python
from preader import IteratorOptions
options = IteratorOptions(start=2)
lines = reader.lines("data.txt", align_start=True, options=options)