How to read text files in Python?

Python provides many built-in functions to perform various file operations, such as creating, reading, and writing text files. Python can handle mainly two types of files: plain text files and binary files. In this guide, we will learn how to read text files in Python.

To read a text file in Python, you need to follow these steps:

  • Step 1: The file needs to be opened for reading using the open() method and the path to the file needs to be passed to the function.

  • Step 2: The next step is to read the file and this can be done using several built-in methods like read(), readline(), readlines().

  • Step 3: After completing the reading operation, the text file must be closed using the close() function.

Now that we have covered the steps to read the contents of a file, let's understand each of these methods before moving on to examples.

open() function in Python

The open() function opens a file, if possible, and returns the corresponding file object.

The syntax looks like this: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

The open() function has many parameters. Let's look at the most necessary parameters for reading a text file. This function opens a file in a given mode and returns a file object.

Parameters

file – an object that represents the path to a file

mode (optional) – is an optional parameter. It is a string that specifies the mode in which you want to open the file.

Mode

Description

'r'

Open file for reading (if the mode is not explicitly specified, this mode is used by default).

'w'

Open a file for writing. Python will create a new file if it does not exist, or clear the file's contents if it does.

'x'

Open file for exclusive creation. (If file already exists – exception).

'a'

Open file to add text. Creates a new file if the file does not exist.

't'

Open file in text mode. (default mode)

'b'

Open file in binary mode.

'+'

Open file for update (read and write).

Example

file = open('C:\hellouser.txt','r')

Methods for reading file contents

There are three ways to read data from a text file.

  • read() : The read() function returns the characters read as a string. This method is good when you have a small file and you want to read a certain number of characters or the entire file and store them in a string variable.

  • readline() : The **readline() **function returns a single line from a text file as a string.

  • readlines(): The **readlines() **function reads all lines from a text file and returns each line as a string element in a list.

Python close() function

In Python, a file will remain open until you close the file using the close() function. It is a good practice to do this after reading data from the file, as this frees up the memory space occupied by the file.

Examples of reading a text file in Python

Example 1 – Reading a text file using the read() function

In the example below, we read the entire text file using the read() method. The file can be opened in read mode or text mode to read the data, and it can be stored in a string variable.

# Программа для чтения всего файла с использованием функции read()
file = open("hellouser.txt", "r")
content = file.read()
print(content)
file.close()

# Программа для чтения всего файла (полный путь) с помощью функции read()
file = open("C:/Projects/Pythontextreading/hellouser.txt", "r")
content = file.read()
print(content)
file.close()

Result

Dear User, 
Welcome to this guide!
Thank you for reading.
I hope it is helpful for you!
Kind regards,
Valentin Shashkin

Example 2 – Reading a specific number of characters from a text file using the read() function

Sometimes you need to read a certain number of characters from a file. In this case, you can use the read() function by specifying the number of characters you need. The method will output only the specified number of characters in the file, as shown below.

# Программа для чтения определенного количества
# символов в файле с помощью функции read()
file = open("hellouser.txt", "r")
content = file.read(20)
print(content)
file.close()

Result

Dear User,
Welcome

Example 3 – Reading a single line from a file using the readline() function

If you only need to read one line from a file, you can do so using the readline() function. You can also use this method to extract a specific number of characters from a line, similar to the read() method.

# Программа для чтения одной строки в файле с помощью 
file = open("hellouser.txt", "r")
content = file.readline()
print(content)
file.close()

Result

Dear User, 

Example 4. Reading a text file line by line using the readline() function

If you want to go through the file line by line and output in any format, then you can use the while loop with the readline() method as shown below. This is the most efficient way to read a text file line by line in Python.

# Программа для чтения всех строк в файле с помощью функции readline()
file = open("hellouser.txt", "r")
while True:
	content=file.readline()
	if not content:
		break
	print(content)
file.close()

Result

Dear User, 
Welcome to this guide!
Thank you for reading.
I hope it is helpful for you!
Kind regards,
Valentin Shashkin

Example 5 – Read all lines as a list in a file using readlines() function

The readlines() method will read all the lines in the file and output the lines as a list as shown below. You can then iterate over this list to extract the content you want.

# Программа для чтения всех строк в виде списка в файле
# с использованием функции readlines()
file = open("hellouser.txt", "r")
content=file.readlines()
print(content)
file.close()

Result

['Dear User,\n', 'Welcome to this guide!\n', 'Thank you for reading.\n', 'I hope it is helpful for you!\n', 'Kind regards,\n', 'Valentin Shashkin']

I wish you success in your studies and hope that this short guide helped you!

Similar Posts

Leave a Reply

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