Here is a clear, complete, and exam-oriented explanation of the read() and write() methods in Python file handling
⭐ read() and write() Methods in Python
In Python, file handling is performed using built-in functions, and two of the most commonly used methods are:
read()→ used to read data from a filewrite()→ used to write data into a file
These methods work only when the file is opened in appropriate mode.
——————————————
⭐ 1. read() Method
The read() method reads data from a file.
You can read the entire file or a specific number of characters.
✔ Syntax
file_object.read(size)
Parameters
size(optional): number of characters/bytes to read- If size is not given, it reads the entire file.
✔ Example 1: Read entire file
f = open("data.txt", "r")
content = f.read()
print(content)
f.close()
✔ Example 2: Read first N characters
f = open("data.txt", "r")
print(f.read(10)) # reads first 10 characters
f.close()
✔ Example 3: Read file in parts (useful for large files)
f = open("data.txt", "r")
print(f.read(5)) # first 5 chars
print(f.read(5)) # next 5 chars
f.close()
💡 Each call to read() moves the file pointer forward.
✔ Example 4: Handling empty file or end of file (EOF)
data = f.read()
if data == "":
print("Reached end of file")
——————————————
⭐ 2. write() Method
The write() method writes a string to a file.
✔ Syntax
file_object.write(string)
Important Notes
- Only string data can be written in text mode
- In write mode
"w", file gets overwritten - In append mode
"a", new data goes to end of file write()returns → number of characters written
✔ Example 1: Writing to a file
f = open("data.txt", "w")
f.write("Hello Python!\n")
f.write("This is file handling.")
f.close()
✔ Example 2: Appending to a file
f = open("data.txt", "a")
f.write("\nThis line is added later.")
f.close()
✔ Example 3: Checking number of characters written
f = open("output.txt", "w")
count = f.write("Python is amazing!")
print("Characters written:", count)
f.close()
——————————————
⭐ Difference Between read() and write()
| Feature | read() | write() |
|---|---|---|
| Purpose | Reads data from file | Writes data to file |
| Modes allowed | "r", "r+", "a+", "w+" | "w", "a", "r+", "w+", "a+" |
| Return value | Content of file | Number of characters written |
| Moves file pointer | Yes | Yes |
| Data type | Returns string | Accepts string |
——————————————
⭐ Best Practice: Use with Block
with open("data.txt", "w") as f:
f.write("Hello Students!")
✔ File closes automatically
✔ Prevents data loss
——————————————
⭐ Exam-Ready Short Answer
The read() method is used to read data from a file. It can read the entire file or a specified number of characters.
The write() method is used to write data into a file and returns the number of characters written. Both methods work on file objects created using the open() function and move the file pointer accordingly.
