How to Read a File Line-by-Line in Python

Created
Modified

Using For Loop

For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:

#!/usr/bin/python3
# -*- coding: utf8 -*-

# read all the lines of a file
with open("file.txt", "r") as f:

  for line in f:
    print(line, end='')
First line.
Second line.

Using f.readlines Method

You can use f.readlines() to read all the lines of a file in a list.

#!/usr/bin/python3
# -*- coding: utf8 -*-

# read all the lines of a file
with open("file.txt", "r") as f:
  lines = f.readlines()

  for line in lines:
    # remove all whitespace characters
    line = line.rstrip()
    print(line)

# read a single line
with open("file.txt", "r") as f:
  line = f.readline()
  print(line, end='')
First line.
Second line.
First line.

A newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.

Using list Method

For example,

#!/usr/bin/python3
# -*- coding: utf8 -*-

# read all the lines of a file
with open("file.txt", "r") as f:

  for line in list(f):
    print(line, end='')
First line.
Second line.

The Available Open Modes

mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode.

modes
'r'
open for reading (default)
'w'
open for writing, truncating the file first
'x'
open for exclusive creation, failing if the file already exists
'a'
open for writing, appending to the end of file if it exists
'b'
binary mode
't'
text mode (default)
'+'
open for updating (reading and writing)

Related Tags

#read# #file# #line#