Python File read() Method – Tutorial with Examples

Python File read() Method

The read() method in Python is a built-in method used to read the contents of a file. It returns a string containing the contents of the file.

Syntax

file.read(size)

The size argument is optional. If it is not specified, the entire contents of the file are read.

Return Value

The read() method returns a string containing the contents of the file.

Examples

Example 1: Basic Usage

In this example, we will create a file, write some data to it, and then read the contents of the file using the read() method:

file = open("example.txt", "w")
file.write("Hello, World!")
file.close()

file = open("example.txt", "r")
data = file.read()
file.close()

print(data)

In this example, we opened a file named “example.txt” in write mode, wrote the string “Hello, World!” to the file, and then closed the file. We then opened the file again in read mode, read the contents of the file using the read() method, and then closed the file. Finally, we printed the contents of the file to the console.

Output:

Hello, World!

Example 2: Reading a Certain Number of Characters

If we only want to read a certain number of characters from a file, we can pass an integer argument to the read() method:

file = open("example.txt", "r")
data = file.read(5)
file.close()

print(data)

In this example, we opened the file named “example.txt” in read mode and read the first 5 characters of the file using the read() method. We then closed the file and printed the contents of the variable data to the console.

Output:

Hello

Example 3: Reading Lines from a File

The read() method can also be used to read individual lines from a file:

file = open("example.txt", "r")
line1 = file.readline()
line2 = file.readline()
file.close()

print(line1)
print(line2)

In this example, we opened the file named “example.txt” in read mode and used the readline() method to read the first two lines of the file. We then closed the file and printed the contents of the variables line1 and line2 to the console.

Output:

Hello, World!

Use Cases

The read() method can be useful in situations where we need to read the contents of a file into memory. This can be useful for performing operations on the data or for displaying it to the user. Additionally, the read() method can be used to read individual lines from a file, which can be useful for parsing text files or other types of data.

Conclusion

The read() method in Python is a powerful tool for reading the contents of files. It can be used to read the entire contents of a file, a certain number of characters from a file, or individual lines from a file. This method is particularly useful for working with text files or other types of data that can be read as strings. By using the read() method, we can easily read data from files and manipulate it in a variety of ways to suit our needs.

Leave a Reply

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