Open and Read a File in Python

This post is lesson 39 of 54 in the subject Python Programming Language

Python provides a simple way to work with files. Whether it is reading from or writing to a file, Python has easy-to-use built-in functions to handle file operations. This document will focus on how to open and read a file in Python.

1. How to Open a File in Python

When working with files, there are three steps that we need to go through:

  1. Opening a file
  2. Reading or Writing a file
  3. Closing the file

Opening a file is the first step. Python provides a built-in function open() to help us open a file with different modes. There are 4 modes when opening a file in Python:

  • r“: Read mode, which is the default mode when opening a file. In this mode, we open a file to read and will encounter an error if we try to open a non-existent file.
  • a“: Append mode. Open a file to add data to it, and create a file if it does not exist.
  • w“: Write mode. Open a file to overwrite data into it, and create a file if it does not exist.
  • x“: Create mode. Create a specific file, and return an error if that file already exists.

Additionally, we can specify whether the file is processed in binary or text mode:

  • t“: Text mode, which is the default mode.
  • b“: Binary mode.

For example, opening a file gochocit.txt in default mode.

f = open("gochocit.txt")

The above command is equivalent to:

f = open("gochocit.txt", "rt")

Since “r” and “t” are default values, we do not need to specify them.

When opening a file in text mode, it is recommended to specify the character encoding to avoid character encoding errors. The character encoding utf-8 is one of the most commonly used character encodings.

f = open("gochocit.txt", "r", encoding="utf-8")

2. How to Read a File in Python

Assume we have a file gochocit.txt in the same directory as the Python code file .py with the following content:

Hello all, welcome to gochocit.com!

Very happy to see you visit gochocit.com.

Hope it might be useful for you!

When using the open() function to open a file, the open() function will return a file object. This object has a read() function to read the data in that file.

f = open("gochocit.txt")
print(f.read())

Output

Hello all, welcome to gochocit.com!
Very happy to see you visit gochocit.com.
Hope it might be useful for you!

If gochocit.txt is located in another directory, we need to provide the exact path of this file when opening the file.

f = open("C:\python-examples\gochocit.txt")
print(f.read())

The read() function helps to read all data in the file. But we can determine the number of characters to read by passing an argument to the read() function.

f = open("gochocit.txt")
print(f.read(10))

Output

Hello all,

If we want to read each line in the file, Python supports the readline() function. The following example is to read 2 lines of the file gochocit.txt.

f = open("gochocit.txt")
print(f.readline(), end='')
print(f.readline(), end='')

Output

Hello all, welcome to gochocit.com!
Very happy to see you visit gochocit.com.

Next, using a for loop is a common way to read each line in the file until the end of the file.

f = open("gochocit.txt")
for x in f:
  print(x, end='')

Output

Hello all, welcome to gochocit.com!
Very happy to see you visit gochocit.com.
Hope it might be useful for you!

3. How to Close a File in Python

After reading/writing a file, we should close the file with close() function.

f = open("gochocit.txt")
print(f.readline())
f.close()

Closing a file is especially necessary when the file is used to read/write data frequently by different programs.

Rate this post
Previous and next lesson in subject<< User-Defined Exception in PythonWrite, Create, and Delete a File in Python >>

Leave a Reply

Your email address will not be published. Required fields are marked *