File Operations in Python
Introduction
• File handling allows us to store data
permanently.
• Python provides built-in functions to
work with files.
• We will learn how to create, read,
write, append, and close files.
File Types
• Text files (.txt) - store readable text.
• CSV files (.csv) - comma separated
values.
• Binary files (.bin) - store non-text
data.
• JSON files (.json) - structured data.
File Modes
• 'r' - Read only
• 'w' - Write (overwrite)
• 'a' - Append
• 'x' - Create new
• 'b' - Binary mode
• 't' - Text mode
Creating a File
Example:
file = open('[Link]', 'w')
[Link]('Hello Python!')
[Link]()
Opening a File
Example:
file = open('[Link]', 'r')
data = [Link]()
print(data)
[Link]()
Reading Files
• read() - reads entire file
• readline() - reads one line
• readlines() - reads all lines into a list
Writing Files
• Write mode ('w') overwrites existing
content.
• Example:
with open('[Link]', 'w') as f:
[Link]('Python is fun!')
Appending Files
• Append mode ('a') adds data at the
end.
• Example:
with open('[Link]', 'a') as f:
[Link]('\nLearn Python!')
Closing Files
• Always close files using close() or use
with-statement for automatic closing.
• Example:
with open('[Link]', 'r') as f:
print([Link]())
OS Module - Directories
• import os
• [Link]('new_folder') - Create
directory
• [Link]() - List files
• [Link]('[Link]') - Delete file
Sys Module
• import sys
• [Link] - Python version
• [Link] - System path
• [Link]() - Exit program
Reading Numbers
Example:
with open('[Link]', 'r') as f:
num = int([Link]())
print(num)
Writing Numbers
Example:
with open('[Link]', 'w') as f:
[Link](str(12345))
CSV Files
• Comma Separated Values
• Example:
import csv
with open('[Link]','w',newline='') as
f:
writer = [Link](f)
[Link](['Name','Age'])
[Link](['Divya',18])
Reading CSV Files
Example:
import csv
with open('[Link]','r') as f:
reader = [Link](f)
for row in reader:
print(row)
TSV Files
• Tab Separated Values
• Example:
with open('[Link]','w') as f:
[Link]('Name\tAge\nDivya\t18')
Binary Files
• Store data in binary format (non-text)
• Example:
with open('[Link]','wb') as f:
[Link](b'Hello')
with open('[Link]','rb') as f:
print([Link]())
Handling File Exceptions
• Use try-except to handle errors
Example:
try:
f = open('[Link]','r')
except FileNotFoundError:
print('File not found')
Using With-Statement
• Automatically closes files
• Cleaner code
Example:
with open('[Link]','r') as f:
data = [Link]()
File Paths
• Absolute path: C:/Users/Divya/[Link]
• Relative path: [Link] (current
directory)
File Operations Flow
Visual diagram idea: Create → Open →
Read/Write/Append → Close
Reading Large Files
• Use loop to read line by line
with open('[Link]') as f:
for line in f:
print([Link]())
Writing Large Files
• Use loops to write multiple lines
with open('[Link]','w') as f:
for i in range(1,101):
[Link](f'Line {i}\n')
Try it Yourself - Activity 1
• Create a text file named
'[Link]'
• Write your name and age in it
• Read the file and print content
Try it Yourself - Activity 2
• Create a CSV file '[Link]'
• Add columns: Name, Subject, Marks
• Add at least 3 rows and print them
Quick Quiz 1
1. Which mode overwrites existing
content?
2. How do you append data to a file?
3. How do you automatically close a
file?
Quick Quiz 2
1. Name two modules used for
file/directory operations.
2. What is the difference between text
and binary files?
3. How to handle file not found errors?
Summary
• File operations: Create, Open, Read,
Write, Append, Close
• OS and Sys modules help with
system tasks
• Handle text, numbers, CSV/TSV, and
binary files
• Always close files and handle
exceptions
References & Resources
• Python Official Docs:
[Link]
[Link]
• CSV module:
[Link]
ml
• OS module:
[Link]
ml