File Handling Basics
Opening Files - The open() Function
The open() function is used to open files in Python. It returns a file object.
file = open ('filename.txt' , 'mode' )
Important: Always close files after use with file.close() or use the with statement for automatic closing.
Reading Methods
read()
Reads entire file content as a single string.
with open ('file.txt' , 'r' ) as f:
content = f.read ()
print (content)
readline()
Reads a single line from the file.
with open ('file.txt' , 'r' ) as f:
line = f.readline ()
print (line)
readlines()
Reads all lines and returns them as a list.
with open ('file.txt' , 'r' ) as f:
lines = f.readlines ()
for line in lines:
print (line)
Iterating Lines
Loop through file line by line (memory efficient).
with open ('file.txt' , 'r' ) as f:
for line in f:
print (line.strip ())
Writing Methods
write()
Writes a string to the file.
with open ('file.txt' , 'w' ) as f:
f.write ('Hello World\n' )
writelines()
Writes a list of strings to the file.
lines = ['Line 1\n' , 'Line 2\n' ]
with open ('file.txt' , 'w' ) as f:
f.writelines (lines)
The with Statement
Best Practice: The with statement automatically closes the file, even if an exception occurs. It's the recommended way to work with files.
file = open ('file.txt' , 'r' )
content = file.read ()
file.close ()
with open ('file.txt' , 'r' ) as file:
content = file.read ()
Interactive Code Simulator
Watch how file operations execute step by step
Reading a File
Writing to a File
Appending to a File
Reading Lines
Using with Statement
Run Simulation
Reset
Virtual File System
Practice file operations in your browser
Create/Write File
Write (w)
Append (a)
Write to File
Read File
Read File
Delete File
Your Files
Operation Log
File Paths & OS Module
Path Types
Absolute Path
Complete path from root directory
'C:\\Users\\John\\Documents\\file.txt'
'/home/john/documents/file.txt'
Relative Path
Path relative to current directory
'file.txt'
'data/file.txt'
'../file.txt'
Interactive Path Builder
/
home
user
documents
data
file.txt
Clear Path
/
Common OS Module Operations
import os
current_dir = os.getcwd ()
if os.path.exists ('file.txt' ):
print ('File exists' )
path = os.path.join ('folder' , 'subfolder' , 'file.txt' )
size = os.path.getsize ('file.txt' )
files = os.listdir ('.' )
Working with CSV Files
CSV Module Basics
import csv
with open ('data.csv' , 'w' , newline='' ) as file:
writer = csv.writer (file)
writer.writerow (['Name' , 'Age' , 'City' ])
writer.writerow (['Alice' , '25' , 'New York' ])
with open ('data.csv' , 'r' ) as file:
reader = csv.reader (file)
for row in reader:
print (row)
Interactive CSV Demo
Generate Sample CSV
Parse CSV
CSV DictWriter & DictReader
import csv
data = [
{'name' : 'Alice' , 'age' : 25, 'city' : 'NYC' },
{'name' : 'Bob' , 'age' : 30, 'city' : 'LA' }
]
with open ('data.csv' , 'w' , newline='' ) as file:
fieldnames = ['name' , 'age' , 'city' ]
writer = csv.DictWriter (file, fieldnames=fieldnames)
writer.writeheader ()
writer.writerows (data)
with open ('data.csv' , 'r' ) as file:
reader = csv.DictReader (file)
for row in reader:
print (row['name' ], row['age' ])
Working with JSON Files
JSON Module Basics
import json
data = {
'name' : 'Alice' ,
'age' : 25,
'skills' : ['Python' , 'JavaScript' ]
}
with open ('data.json' , 'w' ) as file:
json.dump (data, file, indent=4)
with open ('data.json' , 'r' ) as file:
data = json.load (file)
print (data['name' ])
Interactive JSON Demo
Python Dictionary
Convert to JSON File
JSON vs CSV Comparison
Feature
CSV
JSON
Structure
Tabular (rows & columns)
Hierarchical (nested objects)
Data Types
All strings (must convert)
Multiple types (string, number, boolean, null)
Best For
Simple tabular data, spreadsheets
Complex nested data, APIs
Human Readable
Very readable
Readable with formatting
File Size
Smaller for simple data
Larger due to formatting
Exception Handling in File Operations
Common File Exceptions
FileNotFoundError
Raised when trying to open a non-existent file in read mode.
PermissionError
Raised when lacking permission to access a file.
IOError
General input/output operation failure.
IsADirectoryError
Raised when trying to open a directory as a file.
Try-Except-Finally Pattern
try :
with open ('data.txt' , 'r' ) as file:
content = file.read ()
print (content)
except FileNotFoundError:
print ('Error: File not found!' )
except PermissionError:
print ('Error: No permission to read file!' )
except Exception as e:
print (f'Unexpected error: {e}' )
finally :
print ('File operation completed' )
Interactive Exception Handler
Test different exception scenarios:
File Not Found
Permission Error
Successful Read
Write to Read-Only
Test Exception
Best Practices
1. Use Specific Exceptions: Catch specific exceptions before general ones.
2. Use 'with' Statement: Ensures file is closed even if exception occurs.
3. Provide Helpful Messages: Tell users what went wrong and how to fix it.
4. Log Errors: In production, log errors for debugging.
Complete Exception Handling Example
import os
def safe_file_read (filename):
"""Safely read a file with proper exception handling"""
if not os.path.exists (filename):
return None , "File does not exist"
try :
with open (filename, 'r' , encoding='utf-8' ) as file:
content = file.read ()
return content, None
except PermissionError:
return None , "Permission denied"
except UnicodeDecodeError:
return None , "File encoding error"
except Exception as e:
return None , f"Unexpected error: { str (e)}"
content, error = safe_file_read ('data.txt' )
if error:
print (f"Error: {error}" )
else :
print (content)
File Handling Quiz
Test your knowledge of Python file handling concepts
Submit Quiz