Python File Handling: Detailed Notes
1. Introduction to Files in Python
A file is a collection of data stored on a storage device. Python allows handling files easily
for reading and writing operations.
Types of files:
• Text Files (.txt, .csv, .log)
• Binary Files (.bin, .dat)
2. Opening a File
Python uses the open() function to open files.
Syntax:
open(filename, mode)
Modes:
• 'r' - Read (default)
• 'w' - Write (overwrites file)
• 'a' - Append
• 'x' - Create new file
• 'b' - Binary mode
• 't' - Text mode
Example:
f = open('[Link]', 'r')
Python File Modes with Examples
1. Read Mode ('r')
Opens a file for reading. Raises error if file does not exist.
Example:
f = open('[Link]', 'r')
data = [Link]()
print(data)
[Link]()
2. Write Mode ('w')
Creates a new file or overwrites existing content.
Example:
f = open('[Link]', 'w')
[Link]('Hello, this is new content')
[Link]()
3. Append Mode ('a')
Adds content to the end of the file.
Example:
f = open('[Link]', 'a')
[Link]('\nThis line is appended')
[Link]()
4. Create Mode ('x')
Creates a new file. Raises error if file exists.
Example:
f = open('[Link]', 'x')
[Link]('File created successfully')
[Link]()
5. Binary Mode ('b')
Used for binary files like images.
Example:
f = open('[Link]', 'rb')
data = [Link]()
print(type(data))
[Link]()
6. Text Mode ('t')
Default mode for text files.
Example:
f = open('[Link]', 'rt')
data = [Link]()
print(data)
[Link]()
7. Combined Modes
Examples:
open('[Link]', 'rb')
open('[Link]', 'wb')
open('[Link]', 'rt')
8. Best Practice (with statement)
Example:
with open('[Link]', 'r') as f:
print([Link]())
3. Reading from Text Files
Methods:
• read() - Reads entire file
• readline() - Reads one line
• readlines() - Reads all lines as list
Example:
f = open('[Link]', 'r')
print([Link]())
[Link]()
# Example: readline()
with open("[Link]", "r") as f:
line1 = [Link]()
print("First line:", line1)
line2 = [Link]()
print("Second line:", line2)
# Example: readlines()
with open("[Link]", "r") as f:
lines = [Link]()
print(lines)
4. Writing to Files
Modes: 'w' and 'a'
• 'w' overwrites file
• 'a' appends data
Example:
f = open('[Link]', 'w')
[Link]('Hello World')
[Link]()
5. Using with Statement
Automatically closes file after operation.
Example:
with open('[Link]', 'r') as f:
data = [Link]()
6. Working with Text Files
Example:
with open('[Link]', 'w') as f:
[Link]('Line1\nLine2')
7. Advantages of File Handling
• Data persistence
• Easy storage and retrieval
• Useful for large datasets