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. Advantages of File Handling
• Data persistence
• Easy storage and retrieval
• Useful for large datasets
3. 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
Example: f = open('[Link]', 'r')
Create File (‘x’)
f = open('[Link]', 'x')
[Link]('File created successfully')
[Link]()
Read File (‘r’)
f = open('[Link]', 'r')
data = [Link]()
print(data)
[Link]()
Write Mode ('w')
Creates a new file or overwrites existing content.
Example:
f = open('[Link]', 'w')
[Link]('Hello, this is new content')
[Link]()
Append Mode ('a')
Adds content to the end of the file.
Example:
f = open('[Link]', 'a')
[Link]('\nThis line is appended')
[Link]()
Best Practice (with statement)
Example:
with open('[Link]', 'r') as f:
print([Link]())
Reading from Text Files
Methods:
• read() - Reads entire file
• readline() - Reads one line
• readlines() - Reads all lines as list
# 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)
with open('[Link]','w') as f:
[Link]('content rewritten')