python
readlines
file-handling
string-manipulation
duplicate-question

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.

Browse interview questions

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

python
1with open('data.txt') as f:
2    lines = f.readlines()
3    print(lines)
4# ['first line\n', 'second line\n', 'third line\n']
5
6# The \n causes problems:
7print(lines[0] == 'first line')  # False — because of \n

Method 1: List Comprehension with strip()

The most common and idiomatic approach:

python
1with open('data.txt') as f:
2    lines = [line.strip() for line in f]
3
4print(lines)  # ['first line', 'second line', 'third line']

str.strip() removes all leading and trailing whitespace (spaces, tabs, newlines). If you only want to remove trailing newlines:

python
lines = [line.rstrip('\n') for line in f]
MethodWhat 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:

python
1with open('data.txt') as f:
2    lines = f.read().splitlines()
3
4print(lines)  # ['first line', 'second line', 'third line']

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

python
1with open('data.txt') as f:
2    lines = list(map(str.strip, f))
3
4print(lines)  # ['first line', 'second line', 'third line']

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:

python
1# Process line by line (memory-efficient for large files)
2with open('data.txt') as f:
3    for line in f:
4        line = line.rstrip('\n')
5        process(line)
6
7# Build a list
8with open('data.txt') as f:
9    lines = []
10    for line in f:
11        lines.append(line.rstrip('\n'))

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+)

python
1from pathlib import Path
2
3# Read and split in one call
4lines = Path('data.txt').read_text().splitlines()
5print(lines)  # ['first line', 'second line', 'third line']

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:

OSLine endingEscape
Linux/macOSLF\n
WindowsCRLF\r\n
Old macOSCR\r
python
1# Python's open() in text mode handles this automatically
2# It converts all line endings to \n by default
3with open('windows_file.txt') as f:
4    lines = f.read().splitlines()
5# Works correctly regardless of the file's original line endings
6
7# To preserve original line endings, use binary mode
8with open('file.txt', 'rb') as f:
9    raw = f.read()
10    print(raw)  # b'line1\r\nline2\r\n'

Processing CSV or Tab-Separated Data

When reading structured data, strip newlines before splitting:

python
1with open('data.csv') as f:
2    for line in f:
3        fields = line.strip().split(',')
4        name, age, city = fields
5        print(f"{name} is {age} from {city}")

For proper CSV parsing, use the csv module instead:

python
1import csv
2
3with open('data.csv') as f:
4    reader = csv.reader(f)
5    for row in reader:
6        # Rows are already split and stripped
7        print(row)

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 with b'\n' or b'\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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.