Topic 15: File Handling in Python
File Handling in Python
Python provides built-in functions and methods to create, read, write, and delete files easily.
Why File Handling?
-
To store data permanently for future use.
-
To read or process existing data stored in text or binary files.
-
To log information, such as errors or results, during program execution.
-
To exchange data between programs.
File Operations in Python
Python provides four basic operations for handling files:
| Operation | Description | Function |
|---|---|---|
| Open | Opens a file for reading/writing | open() |
| Read | Reads the content of a file | read(), readline(), readlines() |
| Write | Writes data to a file | write(), writelines() |
| Close | Closes an opened file | close() |
Opening a File
file = open("example.txt", "r")
Modes of Opening a File
| Mode | Description |
|---|---|
'r' |
Read mode (default) |
'w' |
Write mode (overwrites existing content) |
'a' |
Append mode (adds data to end of file) |
'x' |
Creates a new file and opens it for writing |
'r+' |
Read and write mode |
'b' |
Binary mode (used for images, PDFs, etc.) |
't' |
Text mode (default) |
Example:
f = open("data.txt", "w")
f.write("Hello Python!")
f.close()
Reading from a File
f = open("data.txt", "r")
content = f.read()
print(content)
f.close()
Other Reading Methods
f.readline() # Reads one line at a time
f.readlines() # Reads all lines and returns a list
Example:
f = open("data.txt", "r")
for line in f:
print(line.strip())
f.close()
Writing to a File
f = open("data.txt", "w")
f.write("This is a new line.")
f.close()
Appending new data:
f = open("data.txt", "a")
f.write("\nAppended line!")
f.close()
Using with Statement (Best Practice)
Python provides the with statement to automatically close the file after its use.
with open("data.txt", "r") as f:
data = f.read()
print(data)
# File is automatically closed
This is preferred because it avoids file corruption and resource leaks.
Working with Binary Files
Binary files store data in bytes (e.g., images, videos, audio).
with open("image.jpg", "rb") as f:
data = f.read()
print(type(data)) # <class 'bytes'>
To write binary data:
with open("copy.jpg", "wb") as f:
f.write(data)
Checking File Existence
Use the os module:
import os
if os.path.exists("data.txt"):
print("File exists.")
else:
print("File not found.")
Deleting a File
import os
os.remove("data.txt")
Visual Flowchart of File Handling

File Handling
Conclusion
File handling in Python simplifies working with external files for permanent data storage.
By using proper file modes, error handling, and the with statement, you can create efficient and reliable programs that interact with files seamlessly.
Comments
Post a Comment