Unit 3: Files, exceptions and visualization
Python Programming notes · PTU syllabus (UGSEC2507)
On this page
Unit summary
Programs must store data permanently, cope with errors gracefully and present results visually. This unit covers text and binary files, the pickle module, CSV and JSON files, exception handling with try-except-else-finally and raise, and plotting graphs with Matplotlib.
After this unit you can
- Read and write text, binary, CSV and JSON files and use pickle
- Handle exceptions with try, except, else, finally and raise
- Explain the exception hierarchy
- Plot line, 3-D, histogram, pie, sine and cosine graphs
PTU syllabus topics
- File types
- creating/reading/writing text and binary files
- the Pickle module
- reading/writing CSV and JSON files
- try-except-else-finally
- raise statement
- exception hierarchy
- plotting 2D and 3D graphics
- histograms
- pie charts
- sine and cosine curves
- 1try
Code that may raise an error
- 2except
Handle a specific error
- 3else
Runs if no error occurred
- 4finally
Always runs, e.g. close a file
Topic 1
File handling
pythonwith open("notes.txt", "w") as f: # with closes the file automatically
f.write("Line 1\n")
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())| Mode | Meaning |
|---|---|
| "r" | Read (default) |
| "w" | Write (overwrites) |
| "a" | Append |
| "rb" / "wb" | Read / write binary |
Pickle saves Python objects to binary files: pickle.dump(obj, f) and obj = pickle.load(f).
pythonimport csv, json
with open("data.csv", newline="") as f:
for row in csv.reader(f): print(row)
with open("data.json") as f:
data = json.load(f) # json.dump(obj, f) writesTopic 2
Exception handling
An exception is a run-time error that stops the program unless handled.
pythontry:
a = int(input()); b = int(input())
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Enter numbers only")
else:
print("Division done") # runs if no exception
finally:
print("Program finished") # always runsraise throws an exception yourself: if age < 0: raise ValueError("Age cannot be negative").
Topic 3
Exception hierarchy
Exception
Base of most errors
ArithmeticError
ZeroDivisionError, OverflowError
LookupError
IndexError, KeyError
ValueError and TypeError
Wrong value or type
OSError
FileNotFoundError, PermissionError
Exam tip
Catch specific exceptions first and general ones (Exception) last; a bare except hides bugs.
Topic 4
Data visualisation with Matplotlib
pythonimport matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
plt.legend(); plt.title("Sine and cosine"); plt.show()
plt.hist([45, 60, 72, 72, 85, 90], bins=5); plt.show()
plt.pie([40, 35, 25], labels=["BCA", "BBA", "B.Com"], autopct="%1.0f%%"); plt.show()3-D plots use from mpl_toolkits.mplot3d import Axes3D and ax = plt.axes(projection="3d").
Key terms
- with statement
- Opens a file and closes it automatically
- Pickle
- Module that serialises Python objects to binary
- Exception
- An error that occurs at run time
- finally
- A block that always executes
- Matplotlib
- Python's main plotting library
Quick revision
- Modes r, w, a, rb, wb; use with to auto-close.
- csv.reader / json.load / pickle.load for different formats.
- try → except → else → finally; raise to throw.
- plt.plot, plt.hist, plt.pie, projection="3d".
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.Why is the with statement used for files?
- Q2.What is pickling?
- Q3.Differentiate between the else and finally blocks.
- Q4.What does raise do?
- Q5.Name three built-in exceptions.
Long-answer questions
- Q1.Explain file handling in Python for text, binary, CSV and JSON files.
- Q2.Explain exception handling in Python with an example using all four blocks.
- Q3.Write Python programs to plot sine and cosine curves, a histogram and a pie chart.
Stuck on this unit?
Message SBS on WhatsApp for help with Python Programming, or to ask about studying BCA at Synetic.
