Getting rid of n when using .readlines
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
When reading a text file with Python's .readlines(), each line in the returned list includes the trailing newline character \n. This is usually unwanted — it causes issues with comparisons, parsing, and display. Python provides several ways to strip these newlines: .strip(), .rstrip(), .splitlines(), and list comprehensions.
The Problem
Method 1: List Comprehension with strip()
The most common and idiomatic approach:
str.strip() removes all leading and trailing whitespace (spaces, tabs, newlines). If you only want to remove trailing newlines:
| Method | What it removes |
.strip() | All leading and trailing whitespace |
.rstrip() | All trailing whitespace |
.rstrip('\n') | Only trailing newlines |
.lstrip() | All leading whitespace |
Method 2: str.splitlines()
Read the entire file and split on line boundaries:
splitlines() handles all line ending styles (\n, \r\n, \r) and does not include the line endings in the result. This is the cleanest one-liner.
Method 3: map() with str.strip
map(str.strip, f) applies .strip() to each line. Wrap in list() to materialize the result.
Method 4: Iterate Without readlines()
You rarely need .readlines() at all — iterating over the file object yields one line at a time:
Iterating over f directly is more memory-efficient than .readlines() for large files, because it reads one line at a time instead of loading the entire file into memory.
Method 5: pathlib (Python 3.5+)
Path.read_text() reads the entire file as a string, and .splitlines() splits without including newlines.
Handling Different Line Endings
Files from different operating systems use different line endings:
| OS | Line ending | Escape |
| Linux/macOS | LF | \n |
| Windows | CRLF | \r\n |
| Old macOS | CR | \r |
Processing CSV or Tab-Separated Data
When reading structured data, strip newlines before splitting:
For proper CSV parsing, use the csv module instead:
Common Pitfalls
.strip()removes all whitespace: If your lines have meaningful leading/trailing spaces,.strip()removes them. Use.rstrip('\n')to remove only the newline.- Last line may not have
\n: The last line of a file often lacks a trailing newline..strip()and.rstrip('\n')handle this correctly (they are no-ops on strings without the target characters). - Empty lines become empty strings: After stripping, blank lines become
''. Filter them out if needed:[line.strip() for line in f if line.strip()]. - Memory with large files:
.readlines()and.read().splitlines()load the entire file into memory. For files larger than available RAM, iterate line by line:for line in f. - Binary mode: In binary mode (
'rb'), lines end withb'\n'orb'\r\n'. Use.decode()first, or open in text mode ('r') for automatic line ending handling.
Summary
- Use
[line.strip() for line in f]to read all lines without newlines (most common) - Use
f.read().splitlines()for a clean one-liner that handles all line ending styles - Use
line.rstrip('\n')when you want to preserve leading/trailing spaces but remove only the newline - Avoid
.readlines()— iterate over the file object directly for memory efficiency - Use
Path('file.txt').read_text().splitlines()for the most concise pathlib approach
Related reading
- Getting S3 objects' last modified datetimes with boto
- Getting started with secure AWS CloudFront streaming with Python
- Getting tensorflow is not a supported wheel on this platform
- Getting the class name of an instance
- Getting the docstring from a function
- Getting the exception value in Python
- getting the index of a row in a pandas apply function
- Getting the index of the returned max or min item using max/min on a list
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.