0% found this document useful (0 votes)
5 views3 pages

File Handling and Exceptions Examples

This document provides comprehensive notes on file handling and exceptions in Python, covering text, CSV, JSON, and binary files, along with their respective reading and writing methods. It also explains exception handling, directory traversal, file automation, and includes a case study on a log file analyzer that demonstrates error handling. Key concepts include using the appropriate modules and functions for file operations and managing errors effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

File Handling and Exceptions Examples

This document provides comprehensive notes on file handling and exceptions in Python, covering text, CSV, JSON, and binary files, along with their respective reading and writing methods. It also explains exception handling, directory traversal, file automation, and includes a case study on a log file analyzer that demonstrates error handling. Key concepts include using the appropriate modules and functions for file operations and managing errors effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

File Handling and Exceptions – Python Notes

1. Reading/Writing Text Files


 Definition: A text file stores data in readable text format. Python allows opening,
reading, writing, and appending text files using the open() function.
 Modes: r – read, w – write (overwrites existing content), a – append (adds data to end),
b – binary mode, x – create new file (error if exists).
 Read operations: [Link]() – reads entire file, [Link]() – reads one line, [Link]() –
returns list of lines.
 Write operations: [Link]('Hello'), [Link](['a\n','b\n']).
 With statement ensures automatic closing of file.
 Example:
with open('[Link]', 'w') as f:
[Link]('Hello World')
with open('[Link]', 'r') as f:
print([Link]())

2. CSV Files
 Definition: CSV (Comma Separated Values) files store tabular data in plain text, where
each line represents a row.
 Use csv module: import csv.
 Writing: [Link]([...]) writes a single row, [Link]([...]) writes
multiple rows.
 Reading: for row in reader: print(row).
 Example:
import csv
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](['Name','Age'])
[Link](['Alice',22])
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(row)

3. JSON Files
 Definition: JSON (JavaScript Object Notation) is a lightweight format for storing and
transferring data in key-value pairs.
 Use json module: import json.
 Writing: [Link](data, f) writes JSON data into a file.
 Reading: obj = [Link](f) reads JSON data into a Python dictionary.
 Example:
import json
data = {'name':'Alice','age':22}
with open('[Link]','w') as f:
[Link](data,f)
with open('[Link]','r') as f:
obj = [Link](f)
print(obj['name'])

4. Binary Files
 Definition: Binary files store data in raw binary format (0s and 1s) instead of plain text.
 Writing: with open('[Link]','wb') as f: [Link](b'Hello Binary').
 Reading: with open('[Link]','rb') as f: print([Link]()).
 Example:
with open('[Link]','wb') as f:
[Link](b'Python Binary Data')
with open('[Link]','rb') as f:
print([Link]())

5. Exception Handling
 Definition: Exception handling ensures a program can catch and respond to errors
without crashing.
 Syntax: try block (risky code), except block (handles errors), else block (executes if no
errors), finally block (always executes).
 Custom Exceptions: class MyError(Exception): pass allows creating user-defined errors.
 Example:
try:
x = int('abc')
except ValueError as e:
print('Error:', e)
else:
print('No error occurred')
finally:
print('Execution finished')

6. Directory Traversal & File Automation


 Definition: Python provides modules to manage files and directories automatically.
 os module: [Link]() – get current directory, [Link]() – list files, [Link]() – create
folder, [Link]() – delete file.
 shutil module: [Link]() – copy file, [Link]() – move file.
 glob module: [Link]('*.txt') – list all files with .txt extension.
 Example:
import os, shutil, glob
print([Link]())
[Link]('testdir')
with open('[Link]','w') as f:
[Link]('Sample')
[Link]('[Link]','[Link]')
print([Link]('*.txt'))

7. Case Study: Log File Analyzer with Error Handling


 Definition: A log analyzer scans server log files and extracts useful information such as
errors.
 Explanation: The script opens a log file, searches for lines containing 'ERROR', counts
and displays them.
 It handles errors like FileNotFoundError, PermissionError, and other unexpected issues
using exception handling.
 Example:
import os

def analyze_log(file_path):
try:
with open(file_path,'r') as f:
errors=[line for line in f if 'ERROR' in line]
print('Total Errors:',len(errors))
for e in errors:
print([Link]())
except FileNotFoundError:
print('Log file not found.')
except PermissionError:
print('Permission denied.')
except Exception as e:
print('Unexpected error:', e)
else:
print('Log analysis completed.')
finally:
print('Process finished.')

analyze_log('[Link]')

You might also like