Read

Reading files is a common operation in Python. We often need to read data from text files, CSV files, or other types of files for data processing or other operations. The Python read() function is used to read the content of a file.

Opening a File

Before a file can be read, it needs to be opened. This is done with the open() function. It takes two parameters: file name and mode. The ‘r’ mode is used for reading.

1file = open("example.txt", 'r')

Note

The file should reside in the same directory as the script you’re executing. If it’s located somewhere else, you need to provide the full path to the file.

Reading a File

Once the file is opened, we can read it. Python provides several methods to do this.

The read() Method

This method reads the entire content of the file.

1file = open("example.txt", 'r')
2print(file.read())

The readline() Method

This method reads a single line from the file.

1file = open("example.txt", 'r')
2print(file.readline())

Continously calling readline() reads subsequent lines.

1file = open("example.txt", 'r')
2print(file.readline())
3print(file.readline())

The readlines() Method

This method returns a list where each element is a line in the file.

1file = open("example.txt", 'r')
2print(file.readlines())

Closing a File

After reading a file, it’s a good practice to close it. You can close a file using the close() method.

1file = open("example.txt", 'r')
2print(file.read())
3file.close()

Caution

It’s very important to close files. Not closing a file might lead to data loss, corruption, or other issues.

Using with Statement

The with statement in Python is generally used for exception handling or cleanup tasks. You can use it to read a file. This method also automatically closes the file once the operations are completed.

1with open("example.txt", 'r') as file:
2    print(file.read())