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.