Skip to content

Computer Science · Ch 2 — File Handling in Python

The readlines() method

2.5.3

The readlines() method

The readlines() method

The readlines() method reads all the lines of a file at once and returns them as a list of strings. Each string in the list corresponds to one line from the file, and crucially, each string includes the newline character ('\n') at its end.

How it works in practice:

Suppose you have a file named myfile.txt containing three lines of text. You open it in read mode and call readlines():

>>> myobject = open("myfile.txt", 'r')
>>> print(myobject.readlines())
['Hello everyone\n', 'Writing multiline strings\n', 'This is the third line']
>>> myobject.close()

The output is a list where every line from the file becomes a separate element. Notice the \n at the end of the first two elements — that's the newline character that marks the end of each line in the original file. The last line may or may not have a trailing newline, depending on how the file was created.

Watch out

Because readlines() loads the entire file into memory at once, it is not suitable for very large files. For huge files, reading line by line with a loop or using readline() is safer.

Using split() with readlines()

Often you want to work with individual words rather than whole lines. The split() method (called on each line string) breaks a line into a list of words, using whitespace as the default separator.

>>> myobject = open("myfile.txt", 'r')
>>> d = myobject.readlines()
>>> for line in d:
        words = line.split()
        print(words)

['Hello', 'everyone']
['Writing', 'multiline', 'strings']
['This', 'is', 'the', 'third', 'line']

Here, each line is split into its constituent words, and each word becomes a separate element in a list. The newline character '\n' is simply treated as whitespace and is removed during splitting.

Using splitlines() with readlines()

If you want to keep each line as a single string but without the trailing newline character, use splitlines() instead of split().

>>> for line in d:
        words = line.splitlines()
        print(words)

['Hello everyone']
['Writing multiline strings']
['This is the third line']

Notice the difference: splitlines() returns each line as a single-element list containing the line text without '\n'. This is useful when you need to preserve the line structure but strip the newline characters.

Tip

splitlines() works on a single string and returns a list of lines. When called on a line that already ends with '\n', it removes that newline. It is different from split() which breaks the line into words.

A Complete Program: Writing and Reading a Text File

Program 2-1 in the textbook demonstrates the full cycle of writing user input to a file and then reading it back.

# Program 2-1: Writing and reading to a text file
fobject = open("testfile.txt", "w")          # creating a data file
sentence = input("Enter the contents to be written in the file: ")
fobject.write(sentence)                      # Writing data to the file
fobject.close()                              # Closing a file

print("Now reading the contents of the file: ")
fobject = open("testfile.txt", "r")          # opening in read mode
for str in fobject:                          # looping over the file object
    print(str)
fobject.close()

How it works step by step:

  1. The file testfile.txt is opened in write mode ("w"). The file handle fobject is returned.
  2. The program accepts a string from the user via input() and stores it in the variable sentence.
  3. The write() method writes that string into the file.
  4. The file is closed with close().
  5. The file is reopened in read mode ("r").
  6. A for loop iterates over the file object directly. In Python, a file object is an iterator — each iteration reads one line from the file (including its newline character) until the end of file is reached. …