← Programming Concepts in Mechanical Engineering (25ME34I)
File Handling and Exception Handling
Programming Concepts in Mechanical Engineering (25ME34I) · C-25 Diploma Mechanical, Semester III
Read with diagrams, search and self-test
After studying this chapter you will be able to:
• Open, read, write, append and close text files using open(), read(), write() and close().
• Use the with statement for safe file handling.
• Read and write CSV files that can be opened in Excel (spreadsheet data exchange).
• Handle run-time errors using try, except, else and finally.
• Identify common Python exceptions and raise your own exceptions.
6.1 Why Files?
Variables live in RAM and are lost when the program ends. A file stores data permanently on a disk or SD card. Engineering programs constantly use files: test-rig readings are logged to a file, sensor data from a Raspberry Pi is saved as CSV, results are exported to Excel, and machine settings are read from configuration files. This chapter supports CO-02: moving engineering data between Python and spreadsheet applications.
Types of files:
• Text files (.txt, .csv, .py): human-readable characters arranged in lines.
• Binary files (.jpg, .xlsx, .pdf): data stored in bytes; opened with mode 'b'.
6.2 File Operations
Fig. 6.1 Steps in file handling
Opening a file
file_object = open("filename", "mode")
| Mode | Meaning | If file does not exist | If file exists |
|---|---|---|---|
| 'r' | Read (default) | FileNotFoundError | Reads from start |
| 'w' | Write | Creates new file | Erases old content |
| 'a' | Append | Creates new file | Adds at the end |
| 'x' | Exclusive create | Creates new file | FileExistsError |
| 'r+' | Read and write | FileNotFoundError | Read/write from start |
| 'rb', 'wb' | Binary read/write | as above | as above |
Writing to a file
write(string) writes a string (it does not add a newline automatically; include \ n). writelines(list) writes a list of strings.
f = open("machine_log.txt", "w")
f.write("Machine log - Lathe L01\n")
f.write("Spindle speed: 1200 rpm\n")
f.writelines(["Feed: 0.2 mm/rev\n", "Depth of cut: 1.5 mm\n"])
f.close()
print("File written")File written
Reading from a file
| Method | Returns |
|---|---|
| read() | Entire file as one string |
| read(n) | Next n characters |
| readline() | Next single line (including \n) |
| readlines() | List of all lines |
| for line in f: | Iterates line by line (memory efficient) |
f = open("machine_log.txt", "r")
print(f.read())
f.close()f = open("machine_log.txt")
print("First line :", f.readline().strip())
for ln in f.readlines():
print("Next line :", ln.strip())
f.close()Machine log - Lathe L01 Spindle speed: 1200 rpm Feed: 0.2 mm/rev Depth of cut: 1.5 mm
First line : Machine log - Lathe L01 Next line : Spindle speed: 1200 rpm Next line : Feed: 0.2 mm/rev Next line : Depth of cut: 1.5 mm
Appending to a file
f = open("machine_log.txt", "a")
f.write("Coolant: ON\n")
f.close()
with open("machine_log.txt") as f:
for no, line in enumerate(f, 1):
print(no, line.rstrip())1 Machine log - Lathe L01 2 Spindle speed: 1200 rpm 3 Feed: 0.2 mm/rev 4 Depth of cut: 1.5 mm 5 Coolant: ON
Closing a file and the with statement
close() releases the file and makes sure all data is actually written to the disk. Forgetting it may lose data. The with statement closes the file automatically, even if an error occurs, and is the recommended way:
with open("data.txt", "r") as f:
content = f.read()
# file is closed here automaticallyOther useful file functions
import os
print("Exists?", os.path.exists("machine_log.txt"))
print("Size :", os.path.getsize("machine_log.txt"), "bytes")
with open("machine_log.txt") as f:
f.read(7)
print("Position after reading 7 chars:", f.tell())
f.seek(0)
print("After seek(0):", f.read(7))Exists? True Size : 98 bytes Position after reading 7 chars: 7 After seek(0): Machine
6.3 Working with CSV Files
A CSV (Comma-Separated Values) file is a plain-text table: each line is a row and values are separated by commas. CSV files open directly in Microsoft Excel, LibreOffice Calc and Google Sheets, so CSV is the most common bridge between Python and spreadsheets.
Sample,Reading1,Reading2,Reading3 1,25.02,24.98,25.01 2,25.01,25.03,24.99
Writing a CSV file with the csv module
import csv
rows = [["Specimen", "Load_kN", "Elongation_mm"],
["S1", 10, 0.05], ["S2", 20, 0.10],
["S3", 30, 0.15], ["S4", 40, 0.21],
["S5", 50, 0.27]]
with open("tensile.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
print("tensile.csv created - open it in Excel")tensile.csv created - open it in Excel
Reading a CSV file
import csv
with open("tensile.csv", newline="") as f:
reader = csv.reader(f)
header = next(reader) # first row
print("Columns:", header)
for row in reader:
load = float(row[1]); dl = float(row[2])
print(f"{row[0]}: load {load:4.0f} kN, dL {dl} mm")Columns: ['Specimen', 'Load_kN', 'Elongation_mm'] S1: load 10 kN, dL 0.05 mm S2: load 20 kN, dL 0.1 mm S3: load 30 kN, dL 0.15 mm S4: load 40 kN, dL 0.21 mm S5: load 50 kN, dL 0.27 mm
DictReader and DictWriter
csv.DictReader reads each row as a dictionary keyed by column names, which makes code self-explanatory.
import csv
with open("tensile.csv", newline="") as f:
for r in csv.DictReader(f):
print(r["Specimen"], "->", r["Load_kN"], "kN")S1 -> 10 kN S2 -> 20 kN S3 -> 30 kN S4 -> 40 kN S5 -> 50 kN
pandas for spreadsheet data (preview)
The pandas library reads CSV and Excel files into a table called a DataFrame in one line and is widely used for engineering data. Excel files need read_excel() (with the openpyxl package installed).
import pandas as pd
df = pd.read_csv("tensile.csv")
print(df)
print("Mean load =", df["Load_kN"].mean(), "kN")
df["Stress_MPa"] = df["Load_kN"] * 1000 / 78.5
df.to_csv("tensile_result.csv", index=False)
print("Rows:", len(df), " Columns:", list(df.columns))Specimen Load_kN Elongation_mm 0 S1 10 0.05 1 S2 20 0.10 2 S3 30 0.15 3 S4 40 0.21 4 S5 50 0.27 Mean load = 30.0 kN Rows: 5 Columns: ['Specimen', 'Load_kN', 'Elongation_mm', 'Stress_MPa']
6.4 Errors and Exceptions
Errors in a program are of three kinds:
| Type | When detected | Example |
|---|---|---|
| Syntax error | Before running (while parsing) | Missing colon: if x > 5 |
| Run-time error (exception) | While running | Division by zero, file not found |
| Logical error | Not detected; wrong output | Using + instead of * in a formula |
An exception is an event that occurs during execution and disrupts the normal flow. If not handled, Python stops the program and prints a traceback. Exception handling lets the program catch the error, take corrective action and continue gracefully – essential for machines that must not crash because of one bad sensor reading.
Common built-in exceptions
| Exception | Cause | Example |
|---|---|---|
| ZeroDivisionError | Division or modulus by zero | 10 / 0 |
| ValueError | Right type but invalid value | int("abc") |
| TypeError | Operation on wrong type | "5" + 3 |
| NameError | Variable not defined | print(xyz) |
| IndexError | List index out of range | [1, 2][5] |
| KeyError | Dictionary key not found | d["missing"] |
| FileNotFoundError | File does not exist | open("no.txt") |
| ImportError / ModuleNotFoundError | Module cannot be imported | import maths |
| AttributeError | Object has no such attribute | (5).append(1) |
| IndentationError | Wrong indentation | mis-aligned block |
6.5 try, except, else, finally
Fig. 6.2 Flow of try-except-else-finally
try:
statements that may raise an exception
except ExceptionType1:
handler for ExceptionType1
except (ExceptionType2, ExceptionType3) as e:
handler; e holds the error message
else:
runs only if no exception occurred
finally:
always runs (cleanup: close file, stop motor)• try: contains the risky code.
• except: catches and handles a specific exception. Several except blocks can be written; a bare except: catches everything (use carefully).
• else: runs when the try block succeeds.
• finally: runs in every case – used to release resources such as files, GPIO pins and motors.
try:
a = float(input("Numerator : "))
b = float(input("Denominator: "))
result = a / b
except ZeroDivisionError:
print("Error: denominator cannot be zero")
except ValueError:
print("Error: please enter numbers only")
else:
print("Result =", result)
finally:
print("Calculation attempt finished")Numerator : 100 Denominator: 0 Error: denominator cannot be zero Calculation attempt finished
try:
n = int(input("Number of parts: "))
print("Parts =", n)
except ValueError as e:
print("Invalid input ->", e)Number of parts: abc Invalid input -> invalid literal for int() with base 10: 'abc'
Raising exceptions
raise creates an exception deliberately, for example when a value is physically impossible.
def stress(P, A):
if A <= 0:
raise ValueError("Area must be positive")
return P / Afor area in (400, 0):
try:
print("Stress =", stress(20000, area))
except ValueError as e:
print("Design error:", e)Stress = 50.0 Design error: Area must be positive
Engineering example – robust sensor-data processing
readings = ["72.5", "73.1", "ERR", "74.0", "", "75.2"]
good = []
for r in readings:
try:
good.append(float(r))
except ValueError:
print(f"Skipped bad reading: {r!r}")
print("Valid readings:", good)
print("Average =", round(sum(good) / len(good), 2))Skipped bad reading: 'ERR' Skipped bad reading: '' Valid readings: [72.5, 73.1, 74.0, 75.2] Average = 73.7
6.6 Practice Programs (Week 6)
Program 6.1 – Read a file and count the number of words
Algorithm: Start → open file in read mode → read content → split into words → count words, lines and characters → display → close → Stop.
# Program 6.1: Count words, lines and characters
text = """Python is widely used in mechanical engineering.
It helps in design calculations and data analysis.
Raspberry Pi uses Python for automation."""
with open("sample.txt", "w") as f: # create a test file
f.write(text)with open("sample.txt", "r") as f:
content = f.read()
words = content.split()
lines = content.split("\n")
print("Number of words :", len(words))
print("Number of lines :", len(lines))
print("Number of characters :", len(content))
print("Occurrences of 'Python':", content.count("Python"))Number of words : 21 Number of lines : 3 Number of characters : 140 Occurrences of 'Python': 2
split() without an argument splits at any whitespace (spaces, tabs, new lines), so it counts words correctly even when there are several spaces.
Program 6.2 – Write random numbers to a file and read them back
# Program 6.2: Random numbers to file and back
import random
nums = [random.randint(1, 100) for _ in range(10)]
with open("random_numbers.txt", "w") as f:
for n in nums:
f.write(str(n) + "\n")
print("Written :", nums)read_back = []
with open("random_numbers.txt", "r") as f:
for line in f:
read_back.append(int(line.strip()))
print("Read :", read_back)
print("Sum =", sum(read_back), " Max =", max(read_back),
" Same data?", nums == read_back)Written : [42, 20, 51, 84, 7, 10, 69, 13, 47, 75] Read : [42, 20, 51, 84, 7, 10, 69, 13, 47, 75] Sum = 418 Max = 84 Same data? True
Numbers must be converted to strings with str() before writing and back to integers with int() after reading, because text files store only characters.
Program 6.3 – Handle division by zero using try-except
# Program 6.3: Division by zero handling
def safe_divide():
try:
x = float(input("Enter dividend: "))
y = float(input("Enter divisor : "))
q = x / y
except ZeroDivisionError:
print("Cannot divide by zero! Try again.")
return None
except ValueError:
print("Invalid number!")
return None
else:
print("Quotient =", q)
return q
finally:
print("--- end of attempt ---")safe_divide() safe_divide()
Enter dividend: 50 Enter divisor : 0 Cannot divide by zero! Try again. --- end of attempt --- Enter dividend: 50 Enter divisor : 5 Quotient = 10.0 --- end of attempt ---
Program 6.4 – Read a CSV file and count the number of rows
# Program 6.4: Read CSV and perform basic operations
import csv
# create the data file (normally exported from Excel)
data = [["Part", "Diameter", "Status"],
["P1", 25.01, "OK"], ["P2", 24.97, "REJECT"],
["P3", 25.00, "OK"], ["P4", 25.03, "REJECT"],
["P5", 24.99, "OK"], ["P6", 25.02, "OK"]]
with open("inspection.csv", "w", newline="") as f:
csv.writer(f).writerows(data)count, ok, dsum = 0, 0, 0.0
with open("inspection.csv", newline="") as f:
reader = csv.reader(f)
header = next(reader)
for row in reader:
count += 1
dsum += float(row[1])
if row[2] == "OK":
ok += 1
print("Header :", header)
print("Number of rows :", count)
print("Accepted parts :", ok)
print("Rejected parts :", count - ok)
print(f"Average diameter : {dsum/count:.3f} mm")Header : ['Part', 'Diameter', 'Status'] Number of rows : 6 Accepted parts : 4 Rejected parts : 2 Average diameter : 25.003 mm
Program 6.5 – Log data with time stamps (data logger)
import random, datetime, csv
start = datetime.datetime(2026, 10, 1, 9, 0, 0)
with open("temp_log.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["Time", "Temperature_C"])
for k in range(5):
t = start + datetime.timedelta(minutes=10 * k)
w.writerow([t.strftime("%H:%M"),
round(random.uniform(60, 75), 1)])
with open("temp_log.csv") as f:
print(f.read())Time,Temperature_C 09:00,64.9 09:10,62.3 09:20,69.8 09:30,61.1 09:40,68.0
Program 6.6 – File not found handled gracefully
fname = "settings.cfg"
try:
with open(fname) as f:
print(f.read())
except FileNotFoundError:
print(fname, "not found - creating default settings")
with open(fname, "w") as f:
f.write("speed=1200\nfeed=0.2\n")
finally:
print("Settings check complete")settings.cfg not found - creating default settings Settings check complete
6.7 Solved Exam Questions
Q1. Explain file operations in Python with suitable syntax. (6 marks)
Answer: (1) open() – f = open("data.txt", "r") opens a file in the given mode (r, w, a, r+, b). (2) read() – f.read(), f.readline(), f.readlines() read the whole file, one line or all lines as a list. (3) write() – f.write("text\n") writes a string; writelines() writes a list. (4) close() – f.close() saves and releases the file. The with statement closes the file automatically. See Section 6.2.
Q2. Differentiate between 'w' and 'a' modes.
Answer: 'w' creates a new file or erases the existing content before writing; 'a' keeps existing content and adds new data at the end. Use 'a' for data loggers so that previous readings are not lost.
Q3. What is a CSV file? How is it read and written in Python? Why is it useful for engineers? (6 marks)
Answer: A CSV file stores tabular data as text with values separated by commas. Write with csv.writer(f).writerows(rows) and read with csv.reader(f) or csv.DictReader(f); pandas uses read_csv()/to_csv(). It is useful because it opens directly in Excel, so test data from machines and sensors can be moved between Python and spreadsheets for analysis and reporting (CO-02).
Q4. What is an exception? Explain try, except and finally with an example. (7 marks)
Answer: An exception is a run-time error that interrupts the normal flow, such as ZeroDivisionError or ValueError. try contains risky code, except handles the specific error, else runs when no error occurs and finally always runs for cleanup. Example: Program 6.3.
Q5. List any five common exceptions with their causes.
Answer: See the table in Section 6.4.
6.8 Multiple Choice Questions
1. Which mode opens a file for appending? a) 'r' b) 'w' c) 'a' d) 'x'
Answer: (c) Reason: 'a' adds data at the end without erasing existing content.
2. Opening an existing file in 'w' mode a) adds to the end b) erases its contents c) raises an error d) opens it read-only
Answer: (b) Reason: Write mode truncates the file before writing.
3. readlines() returns a) a string b) a list of lines c) one line d) number of lines
Answer: (b) Reason: Each element of the list is one line including its newline character.
4. The advantage of the with statement is that a) it reads faster b) the file is closed automatically c) it creates backups d) it encrypts the file
Answer: (b) Reason: with ensures close() is called even if an exception occurs.
5. Which module is used for CSV files? a) csvfile b) csv c) excel d) table
Answer: (b) Reason: The standard-library csv module provides reader, writer, DictReader and DictWriter.
6. int("12.5") raises a) TypeError b) ValueError c) ZeroDivisionError d) No error
Answer: (b) Reason: The string is not a valid integer literal although it is the right type.
7. Which block always executes whether or not an exception occurs? a) try b) except c) else d) finally
Answer: (d) Reason: finally is used for cleanup actions that must always happen.
8. The else block of try executes when a) an exception occurs b) no exception occurs c) always d) never
Answer: (b) Reason: else runs only if the try block finishes without error.
9. Opening a non-existent file in 'r' mode raises a) FileNotFoundError b) KeyError c) IOError only on Linux d) Nothing
Answer: (a) Reason: Read mode requires the file to exist.
10. Which statement deliberately creates an exception? a) throw b) raise c) except d) error
Answer: (b) Reason: raise ValueError("message") signals an error condition.
11. "10" + 5 produces a) 15 b) "105" c) TypeError d) ValueError
Answer: (c) Reason: A string and an integer cannot be added.
12. A logical error is a) detected by the interpreter b) a mistake giving wrong output without any error message c) a syntax error d) a missing file
Answer: (b) Reason: The program runs but the result is wrong, e.g. a wrong formula.
13. To write a number n to a text file you must a) write(n) b) write(str(n)) c) write(int(n)) d) print(n)
Answer: (b) Reason: write() accepts only strings.
14. csv.DictReader returns each row as a) list b) tuple c) dictionary d) string
Answer: (c) Reason: Keys are taken from the header row.
15. newline="" is used while opening CSV files to a) add blank lines b) avoid extra blank rows on Windows c) read faster d) delete lines
Answer: (b) Reason: The csv module handles line endings itself; newline="" prevents doubled line breaks.
6.9 Exercises
1. Write a program to copy one text file into another, converting all text to upper case.
2. Store the results of a hardness test (specimen, BHN) in a CSV file and read it back to find the average hardness.
3. Write a program that keeps asking for a valid positive diameter until the user enters one, handling ValueError.
4. Count the number of lines in a file that contain the word "fault".
5. Append the current date and a machine-running-hours reading to a log file each time the program runs.