Python Writing Structured Text
Structured text keeps a fixed shape on each line. Each line holds one record, with fields in the same order.
Write one line each
Each write ends with a newline. The read back shows three clean lines.
with open("scores.txt", "w") as f:
f.write("Ada 95\nBob 88\nCy 71\n")
with open("scores.txt") as f:
print(f.read().strip())Join fields with a mark
join() builds one line from three fields. The file holds two such lines.
with open("cards.txt", "w") as f:
f.write("|".join(["Ada", "95", "A"]) + "\n")
f.write("|".join(["Bob", "88", "B"]) + "\n")
with open("cards.txt") as f:
for line in f:
print(line.strip())Add a header line
The first line names the fields. The lines below hold the records.
with open("team.txt", "w") as f:
f.write("name|score|grade\nAda|95|A\nBob|88|B\n")
with open("team.txt") as f:
for line in f:
print(line.strip())Example
with open("report.txt", "w") as f:
f.write("name|score|grade\nAda|95|A\nBob|88|B\nCy|71|C\n")
with open("report.txt") as f:
header = f.readline()
for line in f:
line = line.strip()
if line == "":
continue
name, score, grade = line.split("|")
print(name, "scored", score, "grade", grade)Key points
- Record: one line that holds one item of data
- Use \n at the end of each line
- Delimiter: a mark that splits fields, like |
- Use "|".join(fields) to build one line from fields
- Use line.split("|") to cut a line back into fields
- A header line names the fields for the lines below
In this example, the program writes a report file first. The first line is a header that names the fields. readline() reads that header line alone. The loop then reads the record lines one by one. split("|") cuts each line into name, score, and grade. Each printout shows one record in plain words.
Note
A missing \n glues two lines into one.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What builds one line from a list of fields?