The read()
function is a method available in Python for file objects. It is used to read and return the contents of the entire file as a single string. When called without arguments, it reads the entire file. The method takes an optional parameter specifying the number of bytes to read from the file. If no argument is provided, or if the argument is negative or None, the entire content of the file is read and returned.
Parameter Values
Parameter | Description |
---|---|
size | An optional integer argument specifying the number of bytes to read. If not specified, the entire file will be read. |
Return Values
The read()
method returns a str
for text mode or bytes
for binary mode.
How to Use read()
in Python
The read()
method reads a specified number of bytes from the file, starting at the current position. If no size is specified, it reads the entire file.
with open('file.txt', 'r') as file:
data = file.read(10)
print(data)
You can use the read()
method without specifying the size to read the entire file content.
with open('data.txt') as file:
content = file.read()
print(content)
By setting the size parameter to 0 in the read()
method, it will read the entire file as a single string.
with open('info.txt', 'r') as file:
full_text = file.read(0)
print(full_text)