Here’s a complete explanation — simple and structured
1. What Is File Handling?
File handling in Python enables programs to store data permanently (unlike variables, which are lost when a program ends). You can use it to work with text files (.txt), binary files (.bin), CSV, JSON, and more.
Python provides a built-in function:
open()
to interact with files.
2. Syntax of open()
file = open("filename", "mode")
Parameters:
filename → Name or path of the file (e.g.,
"data.txt" or "C:/Files/data.txt")
mode → Defines the purpose of opening the file.
3. File Modes
Mode
Meaning
Description
'r'
Read
Opens file for reading (default). Error if file doesn’t exist.
'w'
Write
Opens for writing, creates new file or overwrites existing one.
'a'
Append
Opens for writing, creates new file if missing, adds to end of file.
'r+'
Read & Write
Reads and writes, doesn’t truncate file.
'w+'
Write & Read
Overwrites existing file.
'a+'
Append & Read
Adds new data, can also read existing data.
'x'
Exclusive creation
Creates file; raises error if file exists.
'b'
Binary mode
For binary files (images, audio, etc.). Used as 'rb', 'wb', etc.
't'
Text mode
Default mode for text files.
4. Reading Files
a) Read the whole file
with open("example.txt", "r") as file:
content = file.read()
print(content)
b) Read line by line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
c) Read first N characters
with open("example.txt", "r") as file:
print(file.read(10)) # Reads first 10 characters
5. Writing to Files
a) Overwrite existing content
with open("example.txt", "w") as file:
file.write("This text replaces old content.")
b) Append to file
with open("example.txt", "a") as file:
file.write("\nThis text is added at the end.")
6. Using with Statement (Best Practice)
Using with automatically closes the file after use — even if an error occurs.
Example:
with open("example.txt", "r") as file:
data = file.read()
# file is automatically closed here
Without with, you’d have to close it manually:
file = open("example.txt", "r")
data = file.read()
file.close()
7. Checking If File Exists (Optional)
You can check file existence before opening:
import os
if os.path.exists("example.txt"):
print("File exists")
else:
print("File not found")
8. Working with Binary Files
Example – writing and reading an image:
# Write binary
with open("image_copy.jpg", "wb") as file:
with open("original.jpg", "rb") as source:
file.write(source.read())
9. Deleting Files
import os
os.remove("example.txt")
10. Summary
Operation
Function/Method
Example
Open a file
open()
open("file.txt", "r")
Read file
read(), readline(), readlines()
file.read()
Write to file
write(), writelines()
file.write("text")
Close file
close()
file.close()
Check file exists
os.path.exists()
os.path.exists("file.txt")
Delete file
os.remove()
os.remove("file.txt")
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Here’s a complete explanation — simple and structured
1. What Is File Handling?
Python provides a built-in function:
to interact with files.
2. Syntax of
open()Parameters:
filename→ Name or path of the file (e.g.,"data.txt"or"C:/Files/data.txt")mode→ Defines the purpose of opening the file.3. File Modes
'r''w''a''r+''w+''a+''x''b''rb','wb', etc.'t'4. Reading Files
a) Read the whole file
b) Read line by line
c) Read first N characters
5. Writing to Files
a) Overwrite existing content
b) Append to file
6. Using
withStatement (Best Practice)Using
withautomatically closes the file after use — even if an error occurs.Example:
Without
with, you’d have to close it manually:7. Checking If File Exists (Optional)
You can check file existence before opening:
8. Working with Binary Files
Example – writing and reading an image:
9. Deleting Files
10. Summary
open()open("file.txt", "r")read(),readline(),readlines()file.read()write(),writelines()file.write("text")close()file.close()os.path.exists()os.path.exists("file.txt")os.remove()os.remove("file.txt")