4.2.1.3 - Text and binary files (Python)

4.2.1.3 - Text and binary files (Python)

Read and write persistent text and binary data in Python, agree a record format, and test that files retain the values the program intends to store.

Fields, records and file organisation

A file stores data beyond the lifetime of one program run, so its format must tell another reader how to recover the values.

A field holds one item such as a name or score; a record groups related fields such as one competitor's name and score. A file can contain many records. In a simple text format, Mina,12 is one record with two comma-separated fields. The program must agree the delimiter, field order, type conversions and handling of blank lines. A comma inside a name would make this simple splitting rule ambiguous; a real CSV reader with quoting rules would be needed. Our examples guarantee that names contain no commas.

Text files store encoded characters. Their numbers are character sequences until converted: the text "12" differs from the integer 12. A binary file stores bytes interpreted according to an agreed representation. Binary is not synonymous with encrypted: a known layout can be decoded. File names and extensions suggest a use but do not prove the contents' format.

Opening a file gives a stream positioned within it. Use with open(...) as file: so it closes when the block finishes, including when an exception occurs. Specify the text encoding, and choose the mode deliberately: "r" reads, "w" creates or overwrites, and "a" appends. Overwriting is appropriate for a newly calculated report but would destroy an existing log if used accidentally.

Text-file reading and writing

Reading one line at a time lets a program process records without loading the whole text file into memory.

Each line usually includes its newline character. line.strip() removes surrounding whitespace; split(",") separates the agreed fields; int(score_text) converts the score. If spaces are meaningful, remove only the newline using rstrip("\n") instead. Writing a record does not add a newline automatically: include "\n" to keep records on separate lines.

Read scores and write a filtered report

{"code":"with open("scores.txt", "r", encoding="utf-8") as source, open("passed.txt", "w", encoding="utf-8") as report:\n for line in source:\n name, score_text = line.strip().split(",")\n score = int(score_text)\n if score >= 10:\n report.write(name + "\n")\nwith open("passed.txt", "r", encoding="utf-8") as report:\n print(report.read(), end="")","instructions":"Predict which names will be written, then run. Change the threshold from 10 to 12 and predict the new report. Run again from fresh files. Explain why mode w prevents old results accumulating.","files":[{"name":"scores.txt","content":"Mina,12\nOmar,8\nLuca,10\n"}],"original_filename":"main.py","runtime_profile":"python-console-v1","file_mode":"fresh"}

The first report contains Mina then Luca, each on a separate line. At threshold 12 it contains only Mina. The supplied file is UTF-8 text; passed.txt is created during execution. Each fresh run starts from the supplied file rather than another student's edited filesystem.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account