💻 Module: 07-File-IO-Data • Unabridged Executed Lesson
📑 Download Module Slides (PDF) 🐍 Download Notebook (.ipynb) 📊 Field_WQ_Sonde_Raw_Log.txt

Lesson 22: File I/O & Parsing Dirty Field Probe .txt Logs (with open, -999.0, ERR_PROBE, ND)

The “Boring Stuff” Problem: Manual Find-Replace in Notepad on Messy USGS Sonde Files

Look at Field_WQ_Sonde_Raw_Log.txt in your datasets/ folder. Real field sondes write:

Always read files with Python’s with open(path, encoding="utf-8") as f: context manager (so OS file handles close safely every time), skip # headers cleanly, and explicitly log every fault flag into a QA report!

from pathlib import Path
def data_file(name):
    """Locate a dataset file whether running from SRC_DIR, module folder, HOMEWORK, or EXAMS."""
    for p in [
        Path("datasets") / name,
        Path("../datasets") / name,
        Path("../../datasets") / name,
    ]:
        if p.exists():
            return p
    raise FileNotFoundError(f"Missing dataset {name} in datasets/")
import numpy as np
import matplotlib.pyplot as plt

# Inspect the first 8 raw lines of Field_WQ_Sonde_Raw_Log.txt
sonde_path = data_file("Field_WQ_Sonde_Raw_Log.txt")
with sonde_path.open("r", encoding="utf-8") as f:
    raw_lines = f.read().splitlines()

print("=== Raw Field Sonde Header & Sample Rows ===")
for ln in raw_lines[:8]:
    print(" ", ln)

# Parse cleanly into audited lists with EPA ND substitution (DL = 0.05 -> DL/2 = 0.025 mg/L)
timestamps, ph_vals, do_vals, turb_vals, q_vals, no3_vals = [], [], [], [], [], []
qa_flags = []

for row_num, ln in enumerate(raw_lines, start=1):
    s = ln.strip()
    if not s or s.startswith("#"):
        continue
    cols = [c.strip() for c in s.split(",")]
    ts = cols[0]
    timestamps.append(ts[11:16])   # HH:MM UTC

    def parse_val(tok, name, nd_sub=None):
        if tok == "ERR_PROBE" or tok == "-999.0":
            qa_flags.append((ts, name, tok))
            return np.nan
        if tok == "ND":
            qa_flags.append((ts, name, "ND->DL/2"))
            return nd_sub if nd_sub is not None else np.nan
        return float(tok)

    ph_vals.append(parse_val(cols[2], "pH"))
    do_vals.append(parse_val(cols[3], "DO_mgL"))
    turb_vals.append(parse_val(cols[5], "Turb_NTU"))
    q_vals.append(float(cols[6]))
    no3_vals.append(parse_val(cols[7], "NO3_N_mgL", nd_sub=0.025))

print(f"\nParsed {len(timestamps)} half-hour sonde intervals | QA Flags Logged: {len(qa_flags)}")
for flag in qa_flags:
    print("  [QA FLAG]", flag)

# Compute storm nitrate mass flux (only valid NO3 rows)
no3_a = np.array(no3_vals)
q_a = np.array(q_vals)
m_valid = np.isfinite(no3_a)
fwmc_no3 = np.sum(q_a[m_valid] * no3_a[m_valid]) / np.sum(q_a[m_valid])
print(f"Storm Flow-Weighted Mean Nitrate-N = {fwmc_no3:.2f} mg/L | Peak Discharge = {q_a.max():.1f} m^3/s")

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.6, 3.6))
t_hrs = np.arange(len(timestamps)) * 0.5
ax1.plot(t_hrs, q_a, "o-", color="#0284c7", label="Stream Q [m^3/s]")
ax1.set_title("Audited Sonde Storm Discharge Hydrograph"); ax1.set_xlabel("Time [h]"); ax1.set_ylabel("Flow [m^3/s]"); ax1.grid(True, alpha=0.3)
ax2.plot(t_hrs, turb_vals, "s-", color="#d97706", label="Turbidity [NTU]")
ax2.plot(t_hrs, no3_a * 5.0, "^--", color="#059669", label="NO3-N x 5 [mg/L]")
ax2.set_title("QA/QC Filtered Water-Quality Pulse (-999 & ND Handled)"); ax2.set_xlabel("Time [h]"); ax2.legend(fontsize=8); ax2.grid(True, alpha=0.3)
fig.tight_layout()
File I/O & Parsing Dirty Field Probe .txt Logs (with open, -999.0, ERR_PROBE, ND) Output Plot 1
=== Raw Field Sonde Header & Sample Rows ===
  # STATION_ID: WABASH-GAUGE-07 (Continuous Multiparameter Sonde)
  # PROTOCOL: USGS Field Water-Quality Telemetry (15-min / 30-min log)
  # COLUMNS: timestamp_iso, temp_C, pH, DO_mgL, cond_uScm, turb_NTU, Q_m3s, NO3_N_mgL
  # SENTINELS: -999.0 or ERR_PROBE = optical wiper fault; ND = below detection limit (0.05 mg/L)
  2026-04-14T00:00:00Z, 15.20, 7.59, 9.15, 482.0, 11.50, 18.50, 2.40
  2026-04-14T00:30:00Z, 15.56, 7.59, 9.03, 487.9, 11.50, 18.50, 2.40
  2026-04-14T01:00:00Z, 15.90, 7.58, 8.91, 493.1, 11.50, 18.50, 2.40
  2026-04-14T01:30:00Z, 16.22, 7.57, 8.81, 497.1, 11.50, 18.50, 2.40

Parsed 28 half-hour sonde intervals | QA Flags Logged: 4
  [QA FLAG] ('2026-04-14T03:00:00Z', 'pH', 'ERR_PROBE')
  [QA FLAG] ('2026-04-14T09:30:00Z', 'DO_mgL', '-999.0')
  [QA FLAG] ('2026-04-14T09:30:00Z', 'NO3_N_mgL', 'ND->DL/2')
  [QA FLAG] ('2026-04-14T12:00:00Z', 'Turb_NTU', '-999.0')
Storm Flow-Weighted Mean Nitrate-N = 3.21 mg/L | Peak Discharge = 32.5 m^3/s

Concept Check Questions

  1. Why is with path.open("r", encoding="utf-8") as f: strictly safer than f = open(...) followed by f.close()?
  2. Why did we replace "ND" (below analytical detection limit) with 0.025 (DL/2) instead of 0.0 or leaving "ND" as text?
  3. What happened on fig Panel 2 at hours 12.0 (-999.0 turbidity -> np.nan)? Notice Matplotlib cleanly left a visible data gap instead of plotting an impossible spike down to -999!

Guided Practice Problem 1: Count & Summarize Sonde pH and DO Range After QA/QC

Compute valid count, minimum, maximum, and mean pH and DO_mgL from ph_vals and do_vals above using np.nanmin, np.nanmax, and np.nanmean (NaN-safe NumPy aggregations!).

# Guided Practice 1 Starter
ph_a, do_a = np.array(ph_vals), np.array(do_vals)
print(f"pH Valid ({np.isfinite(ph_a).sum()}/{len(ph_a)}): mean={np.nanmean(ph_a):.2f}, range=[{np.nanmin(ph_a):.2f}, {np.nanmax(ph_a):.2f}]")
print(f"DO Valid ({np.isfinite(do_a).sum()}/{len(do_a)}): mean={np.nanmean(do_a):.2f} mg/L, range=[{np.nanmin(do_a):.2f}, {np.nanmax(do_a):.2f}]")
pH Valid (27/28): mean=7.42, range=[7.31, 7.59]
DO Valid (27/28): mean=9.13 mg/L, range=[8.60, 9.70]