Use Path("file.txt").read_text(encoding="utf-8").splitlines() (and "".join(...) or " ".join(...) if you want a single string instead of a list of lines), or call .replace("\n", "") / .rstrip("\r\n") when reading inside a with open(...) block to strip newline characters cleanly across Windows (\r\n) and Unix (\n) line endings.
Basic Example
from pathlib import Path
# 1. Read file into a single string with all newlines removed
single_line = "".join(Path("notes.txt").read_text(encoding="utf-8").splitlines())
print(single_line)
# 2. Join lines with a single space instead of gluing words together
spaced_text = " ".join(Path("notes.txt").read_text(encoding="utf-8").splitlines())
print(spaced_text)
# 3. Stream line by line with trailing newlines stripped (memory-efficient for large files)
with open("notes.txt", "r", encoding="utf-8") as file:
lines_without_newlines = [line.rstrip("\r\n") for line in file]
Key Details & Edge Cases
- Why
.splitlines()is cleaner than.split("\n")or.replace("\n", ""):.splitlines()handles all universal line breaks (\n,\r\n, and legacy\r) automatically and omits a trailing empty string if the file ends with a final newline (whereas"a\nb\n".split("\n")produces["a", "b", ""]).- Joining with
"".join(...)removes line breaks completely, while" ".join(...)prevents words at the end of one line from merging directly into the first word of the next line.
- Preserving spaces/tabs while stripping only newlines (
line.rstrip("\r\n")vs.line.strip()): Callingline.strip()with no arguments removes all leading and trailing whitespace—including meaningful indentation spaces and tabs. Passline.rstrip("\r\n")(orline.removesuffix("\n")in Python 3.9+) to strip strictly the line-ending characters. - Stripping only the trailing newline at the end of a file (
.rstrip("\r\n")): If a single-value file (such as an API token or config file) contains"secret_token\n"and you only want to remove the trailing newline at EOF while preserving any internal line breaks, use:token = Path("token.txt").read_text(encoding="utf-8").rstrip("\r\n") - Memory efficiency for huge files:
Path.read_text()loads the entire file into memory at once. For multi-gigabyte log files, iterate over the file handle line by line (with open(...) as f:) and callline.rstrip("\r\n")on each line as you process it.
Comparison of Newline-Stripping File Read Methods
| Approach | Return Type | Handles \r\n & \n? |
Preserves Indentation? | Best Used When |
|---|---|---|---|---|
"".join(Path(p).read_text().splitlines()) |
str (all lines merged) |
Yes | Yes | Combining multi-line text into one continuous string without newlines. |
" ".join(Path(p).read_text().splitlines()) |
str (space-separated) |
Yes | Collapses line breaks to " " |
Flattening prose paragraphs so words across line breaks don’t collide. |
Path(p).read_text().rstrip("\r\n") |
str (trailing break removed) |
Yes | Yes | Reading single-line files (e.g., keys, tokens, IDs) with a trailing newline. |
[line.rstrip("\r\n") for line in f] |
list[str] |
Yes | Yes | Reading a file into a list of clean lines without trailing \n characters. |
You must log in or register to comment.
