How to Read a File Line-by-line into a List in Python

Reading a file line-by-line into a list in python is easy using built-in methods like readlines() or list comprehensions, best for large files.

In Python reading a file line-by-line into a list is a common task when working with a text files. Here are multiple ways to achieve this in a clean and efficient way.

Method 1: Using readlines()

Read all lines at once into a list of strings.

python
with open("example.txt", "r") as file:    lines = file.readlines()   print(lines)
Each line becomes an item in the list including newline characters (\n).

Method 2: Using a Loop with append()

Reads lines one by one and appends manually.

python
lines = []with open("example.txt", "r") as file:     for line in file:         lines.append(line)   print(lines)
More memory efficient for large files than readlines().

Method 3: Using List Comprehension

A clean one-liner to read and strip lines.

python
with open("example.txt", "r") as file:    lines = [line.strip() for line in file]   print(lines)
Strips newline characters and gives a clean list of lines.
Also Read: Top Python Based CMS in 2025

Method 4: Reading File Without Newline Characters

If you don’t want trailing \n in your list items.

python
with open("example.txt", "r") as file:    lines = file.read().splitlines()   print(lines)
splitlines() is useful when you want a newline-free version.

Tip

Always use with open(...) to auto close the file. For large files, avoid readlines() unless you really need to load everything at once.
Related

Amazon CloudWatch allows you to run log insights queries using the logs client in Boto3. Below is a step by step guide to querying logs…

28 Oct, 2025

The Kalman Filter is an efficient recursive algorithm used to estimate the state of a system from noisy measurements. In computer vision, it’s commonly used…

21 Oct, 2025

Printing exceptions in python helps to debug issues by giving clear information about what went wrong and where. You can access the exception message or…

15 Oct, 2025