How to open and read a text file in Python

Overview

The open() function helps to load files from the system hard drive to volatile memory. By definition, it takes multiple argument values, but in this shot, we'll only elaborate on path and mode arguments. Multiple built-in methods are available to read file content including read(), readlines(), and readline().

Syntax


open(path, mode)

Parameters

  • path: This represents a string or path-like object which is used to specify a file that is to be loaded.
  • mode: This indicates the mode or rule by which the file will be loaded to running memory. Here, we have a list of different types of modes.

Types of modes

Mode

Description

'+'

Opens a file in both read and write mode

'r'

Opens file for reading only

'w'

Opens file for writing only

'x'

Opens file in exclusive creation mode

'a'

Opens file in append mode. It does not allow to truncate and create a new file by default if does not exist

't'

Opens file in text mode

'b'

Opens file in binary mode

Code example

Now, let's elaborate on how to read any file in Python using a pre-defined open() function. To do that, we need to pass the file name employee.txt as the first argument with the reading mode 'r' as the second argument value.

fd = open('employee.txt','r')

The open('employee.txt','r') loads the employee.txt file in reading mode and returns a file descriptor fd. This file object allows us to interact with the content of the file.

content = fd.read()

The fd.read() reads all text of the file and returns it as a single string object. We can also use fd.readline() or fd.readlines() according to our needs.

  • fd.readline(): This returns every line of the file as a definite string.
  • fd.readlines(): This reads all lines of the file as strings but returns a list of strings.
fd.close()

When we complete our work, it's mandatory to call the close() method to release occupied system resources by loaded file. It demonstrates that we have meticulously performed our obligations on file.

main.py
employee.txt
fd = open('employee.txt','r')
content = fd.read()
print(content)
fd.close()

The main.py file

print(content) prints the contents of a file to a console.

The employee.txt file

This file contains a record of three individuals including their names, designation, salary, and many more.

Free Resources