Lesson 16: Automating Plain-Text Files & Raw Lab Sensor Logs (with open & pathlib)

The “Boring Stuff” Problem: Messy Instrument Text Dumps & Manual Report Writing

Test stands, CNC controllers, finite-element post-processors, and thermocouples do not always hand you spotless Excel workbooks. Most lab hardware writes raw plain-text logs packed with # header comments, blank lines, weird spacing, and occasional "ERR_OPEN_TC" or "-999.0" sensor dropouts (datasets/Lab_Raw_Thermocouple_Log.txt).

Opening a 5,000-line file in Notepad to delete # lines by hand invites mistakes. Instead, let’s automate text parsing and report writing cleanly using Python’s pathlib.Path and with open(...) context managers.


Safe Reading & Writing Rules (pathlib + with open)

  1. Always Use with open(path, mode, encoding="utf-8") as f:: Think of with like an automatic safety interlock—even if an exception occurs mid-file, Python closes the file handle safely so your OS never locks it!
  2. Never Hardcode Windows-Only Backslashes ("C:\\Users\\..."): Use pathlib.Path("datasets") / "Lab_Raw_Thermocouple_Log.txt" so your script works identically on Windows, macOS, and Linux!
  3. Use try / except ValueError Around float() Conversion: Expect corrupt sensor tokens (ERR_OPEN_TC). Catching bad rows logs a warning instead of crashing an entire test pipeline.
from pathlib import Path

# Example 1 (Heat Transfer Rig Automation): Parse Real Raw Lab Log & Flag Sensor Faults
log_path = next(
    p for p in [
        Path("datasets/Lab_Raw_Thermocouple_Log.txt"),
        Path("../datasets/Lab_Raw_Thermocouple_Log.txt"),
    ] if p.exists()
)

clean_records = []
faults = []

with open(log_path, "r", encoding="utf-8") as f:
    for line_num, raw_line in enumerate(f, 1):
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue   # Skip blank lines and instrument comment headers!
        cols = [c.strip() for c in line.split(",")]
        try:
            t_s, vel, tb, tt, ta = [float(x) for x in cols]
        except ValueError:
            faults.append((line_num, f"Non-numeric sensor token in '{line}'"))
            continue

        # Physics sanity check: reject -999.0 sentinel or base colder than ambient!
        if tb < -200.0 or tt < -200.0 or ta < -200.0:
            faults.append((line_num, f"Sentinel dropout (-999) at t={t_s:.1f}s"))
            continue

        clean_records.append((t_s, vel, tb, tt, ta, tb - tt))

print("=== Raw Thermocouple Log Audit Report ===")
print(f"File           : {log_path.name}")
print(f"Valid Rows     : {len(clean_records)}")
print(f"Rejected Faults: {len(faults)}")
for ln, msg in faults:
    print(f"  [Line {ln:2d}] {msg}")

print("\nFirst 4 Clean Validated Readings:")
for row in clean_records[:4]:
    print(f"  t={row[0]:5.1f}s | V={row[1]:4.2f} m/s | T_base={row[2]:.2f} C | T_tip={row[3]:.2f} C | dT_fin={row[5]:.2f} K")
=== Raw Thermocouple Log Audit Report ===
File           : Lab_Raw_Thermocouple_Log.txt
Valid Rows     : 22
Rejected Faults: 2
  [Line 12] Non-numeric sensor token in '35.0,  4.45,   ERR_OPEN_TC,   63.61,  22.42'
  [Line 21] Sentinel dropout (-999) at t=80.0s

First 4 Clean Validated Readings:
  t=  0.0s | V=2.00 m/s | T_base=84.50 C | T_tip=70.30 C | dT_fin=14.20 K
  t=  5.0s | V=2.35 m/s | T_base=84.08 C | T_tip=69.46 C | dT_fin=14.62 K
  t= 10.0s | V=2.70 m/s | T_base=83.54 C | T_tip=68.50 C | dT_fin=15.04 K
  t= 15.0s | V=3.05 m/s | T_base=82.87 C | T_tip=67.41 C | dT_fin=15.46 K
# Example 2: Writing a Clean Formatted Engineering Summary Back Out to Disk
# Using Path.write_text() or 'with open(..., "w")' inside a local output folder
out_report = Path("datasets/_sample_rig_audit_report.txt") if Path("datasets").exists() else Path("../datasets/_sample_rig_audit_report.txt")

avg_fin_drop = sum(r[5] for r in clean_records) / len(clean_records)
max_vel = max(r[1] for r in clean_records)

lines_out = [
    "AUTOMATED LAB TEST-RIG AUDIT REPORT",
    "=" * 45,
    f"Source Log       : {log_path.name}",
    f"Clean Data Count : {len(clean_records)} timestamps",
    f"Rejected Faults  : {len(faults)}",
    f"Max Air Velocity : {max_vel:.2f} m/s",
    f"Mean Fin Drop dT : {avg_fin_drop:.2f} K",
]
with open(out_report, "w", encoding="utf-8") as fw:
    fw.write("\n".join(lines_out) + "\n")

print("Wrote report cleanly ->", out_report)
print(out_report.read_text(encoding="utf-8"))
# Clean up temporary demo report file
out_report.unlink()
Wrote report cleanly -> datasets\_sample_rig_audit_report.txt
AUTOMATED LAB TEST-RIG AUDIT REPORT
=============================================
Source Log       : Lab_Raw_Thermocouple_Log.txt
Clean Data Count : 22 timestamps
Rejected Faults  : 2
Max Air Velocity : 10.05 m/s
Mean Fin Drop dT : 19.03 K

Practice Questions (Concept Check)

  1. What is the difference between opening a file in mode "r", "w", and "a"? Which one silently erases an existing file?!
  2. Why is with open(...) as f: safer than writing f = open(...); ...; f.close()?
  3. What does try / except ValueError let our parser do when encountering "ERR_OPEN_TC"?
  4. Why does Path("datasets") / "file.txt" beat "datasets\\file.txt"?

Guided Practice Problem 1 (Worked Self-Check): Batch Header Scanner for All Website CSVs (pathlib.glob)

Using pathlib.Path.glob("*.csv") on the datasets/ directory, loop across every CSV file automatically, read ONLY its first line (header), and print each filename alongside its number of columns and file size in KB—Automate the Boring Stuff file inventory in 10 lines!

Hint: Use sorted(ds_dir.glob(“*.csv”)) and with open(p, “r”) as f: header = f.readline().strip()

Calling f.readline() reads JUST line 1 instead of loading huge files into RAM!

# Worked Practice Problem 1 Solution: Automated CSV Folder Inspector
ds_dir = Path("datasets") if Path("datasets").is_dir() else Path("../datasets")
print(f"{'Dataset Filename':<48} | {'Cols':>4} | {'Size [KB]':>9}")
print("-" * 68)
for csv_f in sorted(ds_dir.glob("*.csv")):
    with open(csv_f, "r", encoding="utf-8") as f:
        ncols = len(f.readline().strip().split(","))
    kb = csv_f.stat().st_size / 1024.0
    print(f"{csv_f.name:<48} | {ncols:4d} | {kb:9.2f}")
Dataset Filename                                 | Cols | Size [KB]
--------------------------------------------------------------------
Dynamics_Mass_Spring_Accelerometer_Data.csv      |    4 |      0.55
Fluids_Moody_Friction_Dataset.csv                |    8 |      0.74
Fluids_Property_and_Viscosity_Table.csv          |    9 |      0.91
Fluids_Pump_and_Pipe_Network_Data.csv            |   10 |      0.80
HMT_Heat_Exchanger_NTU_Data.csv                  |   10 |      0.85
HMT_Pin_Fin_Heat_Sink_Data.csv                   |    9 |      0.78
HMT_Steel_Quenching_Transient_Data.csv           |    8 |      0.88
ME200_Air_Ideal_Gas_Table.csv                    |    4 |      2.96
ME200_Saturated_Water_Temp_Table.csv             |   18 |      5.66
ME300_Combined_Cycle_Plant_Telemetry.csv         |   10 |      6.95
Solar_Collector_FlatPlate_Hourly_Data.csv        |    5 |      0.61
Solids_Cantilever_Beam_Deflection_Data.csv       |    2 |      0.25
Solids_Tensile_Stress_Strain_RTD_Data.csv        |    5 |      0.61

End-of-Chapter Practice Problems (Try Yourself!)

  1. Export Clean CSV From Faulty Text Log: Read Lab_Raw_Thermocouple_Log.txt, filter out comments and bad sensor rows, compute fin temperature effectiveness (T_base - T_tip)/(T_base - T_amb), and write a clean comma-separated text file in memory/output.
  2. Header Metadata Extractor: Extract ONLY the # comment lines from Lab_Raw_Thermocouple_Log.txt into a metadata dictionary {"LAB_RIG": ..., "OPERATOR": ..., ...}.
  3. Stress-Test Report Writer (Statics): Given a list of (part_id, sigma_MPa, Sy_MPa) records, write a formatted inspection summary file tagging every part whose Sy / sigma < 1.5 as REQUIRES REDESIGN.

🎬 Concept & Engineering Animation

🎬 Lab Log Line Filter Parser