Computer Science · Ch 2 — File Handling in Python
The read() method
The read() method
The read() method is how you pull data out of a file and into your Python program. It reads a specified number of bytes (characters) from the file, starting from the current position of the file pointer.
The syntax is straightforward:
file_object.read(n)
Here, n is the number of bytes you want to read. For example, if you have a file called myfile.txt and you open it in read mode, you can read the first 10 bytes like this:
>>> myobject = open("myfile.txt", 'r')
>>> myobject.read(10)
'Hello ever'
>>> myobject.close()
Notice that read(10) returned exactly the first 10 characters of the file — including the space after "Hello". The file pointer then moves to position 10, so the next read would start from there.
If you call read() with no argument or with a negative number, it reads the entire file content from the current position to the end of the file.
This is a very common usage. For instance:
>>> myobject = open("myfile.txt", 'r')
>>> print(myobject.read())
Hello everyone
Writing multiline strings
This is the third line
>>> myobject.close()
Here, read() without any argument returned the whole file as a single string, including the newline characters that separate the lines. The print() function then displays it with proper line breaks.
A common mistake is to forget that read() without an argument reads the entire file into memory. For very large files, this can consume a lot of RAM. In such cases, it is better to read in chunks using read(n) or to use other methods like readline().
To summarise the behaviour:
| Argument to read() | What it reads |
|---|---| …