0% found this document useful (0 votes)
9 views1 page

File Handling and Exceptions

This document provides notes on file handling and exceptions in Python, covering reading and writing text, CSV, JSON, and binary files. It also discusses exception handling, directory traversal, and file automation using various modules. Additionally, a case study is included that demonstrates a log file analyzer with error handling.
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)
9 views1 page

File Handling and Exceptions

This document provides notes on file handling and exceptions in Python, covering reading and writing text, CSV, JSON, and binary files. It also discusses exception handling, directory traversal, and file automation using various modules. Additionally, a case study is included that demonstrates a log file analyzer with error handling.
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
You are on page 1/ 1

File Handling and Exceptions – Python Notes

1. Reading/Writing Text Files


 Open a file: f = open('file.txt', 'r')
 Modes: r (read), w (write), a (append), b (binary), x (create new)
 Read: f.read(), f.readline(), f.readlines()
 Write: f.write('Hello'), f.writelines(['a\n','b\n'])
 With statement: with open('file.txt','r') as f: data = f.read()

2. CSV Files
 Use csv module
 Writing: writer.writerow([...]), writer.writerows([...])
 Reading: for row in reader: print(row)

3. JSON Files
 Use json module
 Writing: json.dump(data, f)
 Reading: obj = json.load(f)

4. Binary Files
 Write: with open('data.bin','wb') as f: f.write(b'Hello')
 Read: with open('data.bin','rb') as f: print(f.read())

5. Exception Handling
 try-except-else-finally structure
 Custom Exceptions: class MyError(Exception): pass

6. Directory Traversal & File Automation


 os: os.getcwd(), os.listdir(), os.mkdir(), os.remove()
 shutil: shutil.copy(), shutil.move()
 glob: glob.glob('*.txt')

7. Case Study: Log File Analyzer with Error Handling


 Example code provided for analyzing errors in log files with exception handling.

You might also like