read() in Python

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
201561
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
201561
4.90
Start Learning
Topics Covered

Overview

In programming, file management is a key concept. We can add information to our long-term memory thanks to it. The simplicity of programming and elegant capabilities of Python's file management is unmatched. File creation, writing, and reading functions are built into Python. Normal text files and binary files are the two types of files that can be handled in Python. Python's read() function performs one of the most basic operations of file handling, reading from the file. A file serves as a way to store computed information in permanent storage.

Syntax of read() in Python

Located inside a file pointer object, the read() function is a class method. In order to define a file reference and call read() in Python, a file must first be opened.

The syntax of read() in Python is:

Parameters of read() in Python

As seen in the above syntax the read() function in Python takes one parameter:

  • size: optional, the number of characters to read from the file

The size parameter tells the number of characters to read from the file. It is an integer number that reads from the file exactly the given number of characters (or bytes, if the file is opened in binary mode) and returns them as a string or byte array depending on the mode file is opened in.

Example usage of size:

Since the size parameter is optional, the default value it has is -1 which means it will read the entire file.

Return Values of read() in Python

The read() function in Python returns a string or byte array which contains the contents of the file.

Return Type: string or byte array

Example

The following program shows the return value provided by read().

Contents of the sample.txt file are:

Output:

Exceptions of read() in Python

The read() method does not cause any exception that is core to its nature. The read() method will simply return an empty string ('') or empty byte array (b'') if the file has reached its end.

The read() function will return partial contents if the system runs out of memory while reading a large file.

In a very rare scenario when working in an environment with multiple threads and one file being accessed by more than one thread at once the read() function can return PermissionError. This is a non-native exception as the simultaneous access of the same file is handled by the operating system.

Example of read() in Python

Example

The Following Code Snippet Demonstrates the Basic Usage of the read() Function in Python

Contents of the sample.txt file are:

Program

Output:

What is read() in Python?

Up until now, we have seen various bits that make up the read() function. Now, let us have a look at read() as a whole.

The read() function in Python allows us to read the contents of an opened file according to our requirements. This enables us to perform read operations of a specific length.

read() takes an optional argument size and returns the contents in the file as a string or byte array depending upon the mode in which the file is opened. It is useful for file reading operations as it gives us the ability to select a specific length of the contents to read from the file.

A file handle needs to be opened on which the read() function can operate. If the file handle is opened in append write mode ('aw') then any operations done using read() are useless.

To open a file, we use the built-in open() method in Python. In order to read or edit a file appropriately, this method returns a file object, commonly called a handle.

More Examples

For the rest of the examples we are going to use the sample.txt file with the contents:

Example 1

Reading the File Part by Part.

Output:

Explanation:

When we open the file, we have not provided any other arguments after the file name. Hence the file is opened in normal text mode. In the next part of the code, we read the contents of the file in a part-by-part manner from the file and at the end, we read the rest of the file. We provide the size parameter to the read function to limit the reading into parts.

Example 2

Reading a File in Binary Mode

Output:

Note that the read() function returns a byte array (b'') instead of a string since we have opened the file in binary mode ('rb')

Explanation:

Here we have opened the file in binary mode. In binary mode, the size parameter represents the length in terms of bytes and not the number of characters as happens in normal text mode. We can also see that the return type from the read() function is a byte array when the file is opened in binary mode.

Example 3

Reading the Complete Contents of the File into a String

Output

Explanation

Here we have used the with keyword when we open the file. Using the with keyword improves the file handling efficiency as the file remains open only till the with block is executed. We read all the contents of the file in string_var and print them.

Conclusion

In this article, we have understood the working of read() in Python. Along with the following concepts:

  • read() allows us to read a portion of a file or the complete file at once.
  • read() takes an optional argument, size.
    • size is an optional argument, an integer specifying the length of the portion to read.
  • read() returns the contents of the file as either string or byte array.
  • read() does not throw any native exceptions, instead it returns an empty string when the file ends.

See Also

Visit the following topics to learn more about file handling in Python.