Python 3 – File read() Method
In Python, the read()
method is used to read the specified number of bytes or characters from a file. By default, this method reads the entire content of the file as a string. The file should be open in read mode ('r'
) to be able to use this method.
Here’s the basic syntax for using the read()
method:
file_object.read(size)
file_object
: This refers to the file object that was previously opened using theopen()
function.size
: This is an optional parameter which specifies the number of bytes (or characters) to be read from the file. If this parameter is not specified, then the entire content of the file is read.
Let’s take a look at some examples of how to use the read()
method.
Example 1: Reading the Entire File
In this example, we will read the entire contents of a file named “example.txt”:
with open("example.txt", "r") as file:
data = file.read()
print(data)
Output:
Hello, world!
This is an example file.
It contains some text.
Example 2: Reading Specified Number of Characters
In this example, we will read the first 10 characters of a file named “example.txt”:
with open("example.txt", "r") as file:
data = file.read(10)
print(data)
Output:
Hello, wor
Example 3: Reading the File Line by Line
In this example, we will read the entire file line by line:
with open("example.txt", "r") as file:
for line in file:
print(line)
Output:
Hello, world!
This is an example file.
It contains some text.
Example 4: Reading a Binary File
In this example, we will read a binary file named “example.bin”:
with open("example.bin", "rb") as file:
data = file.read()
print(data)
Output (in bytes):
b'\x48\x65\x6c\x6c\x6f\x2c\x20\x77\x6f\x72\x6c\x64\x21'
In this example, we have opened the file in binary mode ('b'
). This is necessary if we want to read files like images or videos.
Conclusion
The read()
method in Python is a useful function for reading files. It can read the entire file or a specified number of bytes/characters, and it can be used to read text files and binary files. Always make sure to close the file when you’re done reading it using the close()
method, or by using the with
statement as shown in the examples above.