In Python, file handling is done using the open() function.
You can perform reading, writing, and appending operations in text or binary mode.
Python provides multiple methods to read and write data depending on the requirement — such as reading line-by-line, reading full content, or writing chunks.
🔹 File Opening Syntax
file = open("filename", mode)| Mode | Description |
|---|---|
'r' | Read (default) |
'w' | Write (overwrites file if exists) |
'a' | Append (adds to end of file) |
'r+' | Read and write |
'w+' | Write and read (creates file if not exists) |
'a+' | Append and read |
'rb' / 'wb' / 'ab' | Binary read/write/append modes |
🧩 1. Writing to a File
Method 1: Using write()
file = open("example.txt", "w")
file.write("Hello, this is a sample text file.\n")
file.write("This is the second line.")
file.close()Output (File content):
Hello, this is a sample text file.
This is the second line.Method 2: Using writelines()
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file = open("lines.txt", "w")
file.writelines(lines)
file.close()Output (File content):
Line 1
Line 2
Line 3Method 3: Using with (Recommended)
with open("data.txt", "w") as file:
file.write("Using 'with' ensures the file closes automatically.")✅ Advantage: No need to manually close the file; it’s handled automatically.
🧩 2. Reading from a File
Assume we have a file sample.txt:
Python is great.
File handling is easy.
Let's learn read methods.Method 1: Using read() — Reads Entire File
with open("sample.txt", "r") as file:
content = file.read()
print(content)Output:
Python is great.
File handling is easy.
Let's learn read methods.Method 2: Using readline() — Reads One Line at a Time
with open("sample.txt", "r") as file:
line1 = file.readline()
line2 = file.readline()
print(line1.strip())
print(line2.strip())Output:
Python is great.
File handling is easy.Method 3: Using readlines() — Reads All Lines into a List
with open("sample.txt", "r") as file:
lines = file.readlines()
print(lines)Output:
['Python is great.\n', 'File handling is easy.\n', "Let's learn read methods.\n"]Method 4: Iterating Over File Object
with open("sample.txt", "r") as file:
for line in file:
print(line.strip())Output:
Python is great.
File handling is easy.
Let's learn read methods.✅ This is memory-efficient for large files.
🧩 3. Appending to a File
To add new content to the end of an existing file, use 'a' mode.
with open("example.txt", "a") as file:
file.write("\nThis line was added later.")Result (File content):
Hello, this is a sample text file.
This is the second line.
This line was added later.🧩 4. Reading and Writing Together (r+, w+, a+)
Example: r+ Mode (Read and Write)
with open("example.txt", "r+") as file:
data = file.read()
print("Before writing:", data)
file.write("\nAdding text using r+ mode.")Example: w+ Mode (Write and Read)
with open("newfile.txt", "w+") as file:
file.write("First line using w+ mode.")
file.seek(0) # Move cursor to the beginning
print(file.read())Output:
First line using w+ mode.🧩 5. Working with Binary Files
For images, videos, or non-text files, use binary mode ('rb' or 'wb').
Reading Binary Data
with open("image.jpg", "rb") as file:
data = file.read()
print("Bytes read:", len(data))Writing Binary Data
with open("copy.jpg", "wb") as file:
file.write(data)🧩 6. Checking File Position (Using tell() and seek())
with open("sample.txt", "r") as file:
print("Current position:", file.tell()) # 0 (start)
content = file.read(10)
print("Read 10 chars:", content)
print("Current position:", file.tell()) # After reading 10 chars
file.seek(0) # Move cursor back to start
print("After seek, position:", file.tell())Output:
Current position: 0
Read 10 chars: Python is
Current position: 10
After seek, position: 0Summary Table
| Operation | Method | Description |
|---|---|---|
| Read entire file | file.read() | Reads full file content |
| Read one line | file.readline() | Reads next line |
| Read all lines | file.readlines() | Returns list of all lines |
| Write to file | file.write() | Writes a string |
| Write multiple lines | file.writelines() | Writes a list of strings |
| Append content | 'a' mode | Adds text at the end |
| Binary read/write | 'rb' / 'wb' | For images or non-text files |
| Move file pointer | file.seek(offset) | Moves cursor |
| Check cursor position | file.tell() | Returns current position |
| Auto close file | with open() | Closes file automatically |
🔹 In Summary
- Use
open()with proper mode ('r','w','a', etc.) for reading/writing files. - Prefer
with open()to automatically manage file closing. - Use
read(),readline(), andreadlines()for different reading needs. - Use binary modes for non-text data.
- Control file position using
seek()andtell()for precise reading/writing.
✅ In short:
Python provides multiple ways (
read(),write(),readlines(),writelines(), etc.) to efficiently read, write, and manage files — best handled using thewith open()context manager.
