Text File Operations
Engineering Text File Processing
Engineering text file processing turns stored measurements into checked numerical inputs and readable results. You encounter it when an instrument exports readings or an analysis program saves a summary. A text file contains characters: a value such as "24.6" becomes a number only after conversion. The Python examples here use simple records with known delimiters and no quoted fields.
Open files with a clear purpose
Before opening a file, identify its path, character encoding, and intended use. A relative path is interpreted from the program's current working directory, which may differ from the directory containing the script. Specify encoding="utf-8" when that matches the file's encoding.
Mode | Purpose | Effect on an existing file |
|---|---|---|
"r" | Read stored text | Preserves its contents |
"w" | Write a replacement | Erases its previous contents when opened |
"a" | Add text at the end | Preserves existing text and appends new text |
Use a context manager so the file closes when its block finishes, including when an exception interrupts processing:
with open("readings.txt", "r", encoding="utf-8") as source:
header = source.readline()The file position is the location from which the next read begins. Reading advances it. After source.read() consumes the remaining contents, a loop over that same file finds no remaining lines unless you reposition or reopen it.
Turn records into numerical values
Parsing means interpreting text according to a specified structure. Establish that structure before calculating: which line is the header, what separates fields, which column contains each quantity, and what units apply?
For example, suppose every data record contains a time in seconds followed by a force in newtons, separated by a comma. For one already checked record:
line = "0.5,24.6\n"
fields = line.strip().split(",")
time_s = float(fields[0])
force_n = float(fields[1])Here, strip() removes surrounding whitespace, split(",") separates the fields, and float() converts their text to numerical values. Splitting alone leaves strings. Simple splitting is appropriate for this stated format; quoted fields containing commas require a parser that understands those quoting rules.
For a complete file, consume and check the header once, then iterate through the remaining lines. Check the field count before indexing. Decide explicitly whether blank lines and missing-value markers are allowed. Report malformed records with their physical line numbers rather than silently treating them as zero.
A summary calculation should use the number of accepted measurements. For their arithmetic mean,
Here, xi is an accepted measurement and n is the accepted count. Headers and blank lines do not contribute observations. If no measurements remain, report that condition instead of dividing by zero. Conversion also does not verify units: a numerical value still needs the meaning supplied by the file specification.
Write results that can be read again
Choose an output structure deliberately. Include column names and units, use consistent delimiters, and format results to the required precision. Keep full numerical precision during calculations; round when preparing output.
with open("summary.txt", "w", encoding="utf-8") as destination:
destination.write("count,mean_force_N\n")
destination.write(f"{count},{mean_force_n:.2f}\n")This snippet assumes count and mean_force_n have already been calculated. The format .2f produces two digits after the decimal point. The write() method adds no newline automatically, so \n supplies each record boundary.
Complete input validation before opening an existing report for replacement. This prevents a malformed input record from destroying that report merely because output was opened too early.
What to remember
- Choose the file mode before opening the path.
- Read, split, validate, and convert before calculating.
- Track accepted measurements separately from physical lines.
- Preserve units and add explicit output record boundaries.
- Format results after calculation and close files with with.
Example: Summarizing a tensile-test text file
A tensile-test instrument saves tensile_readings.txt as UTF-8 text. Its complete contents are shown below, one table row per file line. Each line ends with a newline character. Time is in seconds and force is in newtons.
File line | Contents |
|---|---|
1 | time_s,force_N |
2 | 0.0,126.0 |
3 | 0.5,138.0 |
4 | 1.0,132.0 |
There are no blank lines, missing values, or quoted fields. The input and output paths identify different files.
a) Read the file, check its header and two-field structure, and collect the force measurements as numbers. State the accepted count and total force.
Open the input in read mode and consume the header once. Each remaining line represents one measurement, so split it at the comma and convert both fields. The column order determines which converted value is the force.
forces_n = []
with open("tensile_readings.txt", "r", encoding="utf-8") as source:
header = source.readline().strip()
if header != "time_s,force_N":
raise ValueError("Unexpected header")
for line_number, line in enumerate(source, start=2):
fields = line.strip().split(",")
if len(fields) != 2:
raise ValueError(f"Line {line_number}: expected two fields")
try:
time_s = float(fields[0])
force_n = float(fields[1])
except ValueError as exc:
raise ValueError(
f"Line {line_number}: invalid numeric field"
) from exc
forces_n.append(force_n)The collected values are forces_n = [126.0, 138.0, 132.0], expressed in newtons. The header is excluded from the measurement count:
The accepted count is 3 measurements, and their total is 396.0 N.
b) Calculate the mean force and report it to one decimal place.
Use the accepted count rather than the number of physical file lines. Check that the list is nonempty before dividing, then retain the computed value for later formatting.
count = len(forces_n)
if count == 0:
raise ValueError("No measurements")
mean_force_n = sum(forces_n) / countSubstituting the total and count gives:
The mean is 132.0 N to one decimal place. It lies between ________ and ________, which provides a useful check on the calculation.
c) Replace tensile_summary.txt with a header and one summary record containing the accepted count and mean force. Show the exact two output lines, with the mean formatted to one decimal place.
Input processing and calculation have finished, so open the separate summary path in write mode. Write the header once, then format the count and mean into one comma-separated record. Each write explicitly includes a newline.
with open("tensile_summary.txt", "w", encoding="utf-8") as destination:
destination.write("count,mean_force_N\n")
destination.write(f"{count},{mean_force_n:.1f}\n")The resulting file contains these two lines in order, each followed by a newline:
- count,mean_force_N
- 3,132.0
The count is dimensionless, and the header identifies the force unit as newtons. The .1f format produces one decimal place; leaving the with block closes the output file.
An engineering script processes text files using Python 3. Match each method call to its behaviour. Assume that source is open for reading, target is open for writing, and records is a list of strings.
Returns all remaining text as one string, including any newline characters.
Returns a list of the remaining lines, retaining each ending newline if present.
Writes the supplied strings consecutively without inserting separators between them.
Returns the next line as a string, including its ending newline if present, or an empty string at the end of the file.
source.readline()
source.readlines()
target.writelines(records)
source.read()
A UTF-8 file named forces.txt contains the header force_N, followed by three lines containing 22.0, 28.0, and 34.0, respectively. There are no blank lines. The following Python program unexpectedly prints 0.0:
with open("forces.txt", "r", encoding="utf-8") as source:
header = source.readline()
preview = source.read()
total_n = 0.0
for line in source:
total_n += float(line)
print(total_n)Which single edit makes the loop sum all three measurements without reading the data twice?