Rejecting malformed records explicitly

A Python parser processes engineering records after checking the header time_s,force_N. The specification permits blank lines, but every nonblank data line must contain exactly two comma-separated fields that both convert with float(). Any malformed record must stop processing and identify its physical line number.


The current implementation is:


Python
for line_number, line in enumerate(source, start=2):
    if not line.strip():
        continue
    fields = line.strip().split(",")
    if len(fields) != 2:
        continue
    time_s = float(fields[0])
    force_n = float(fields[1])


Potential malformed records include "1.0,7.2,extra" and "1.5,error". Which revision satisfies the complete specification?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Text File Operations Questions: