Programming with Python · free preview

Files and JSON

Write and read text files, process them line by line, and save structured data as JSON.

1. Overview

Overview

2. Writing a Text File

Writing a Text File

3. Reading Line by Line

Reading Line by Line

4. Appending to a File

Appending to a File

5. Saving Structured Data as JSON

Saving Structured Data as JSON

6. Write and Count

Write and Count

7. A Record as JSON

A Record as JSON

8. Choose the file mode

A program opens log.txt with "w", writes start\n, reopens it with "a", and writes ran analysis\n. What does the file contain?

9. Trace writing, appending, reading, and JSON round trips

Predict each output before running the complete workflow.

Example. Trace writing, appending, reading, and JSON round trips

Problem. Predict each output before running the complete workflow.

Correct solution.

Step 1, write two lines with escaped newlines.

python
with open('notes.txt', 'w') as handle:
 handle.write('first line\n')
 handle.write('second line\n')

No output appears.

Step 2, read back and count.

python
with open('notes.txt') as handle:
    for line in handle:
        print(repr(line))

Output.```output 'first line\n' 'second line\n'

code

Reasoning, line iteration keeps trailing newlines; `repr` makes them visible.

Step 3, append and count.

```python
with open('notes.txt', 'a') as handle:
 handle.write('ran analysis\n')
with open('notes.txt') as handle:
 print(sum(1 for line in handle))

Output.```output 3

code

Reasoning, mode `a` writes after the current end; counting with a generator avoids a line list.

Step 4, save and reload a record.

```python
import json
visit = {'patient': 'Bob', 'readings': [36.9, 37.1], 'discharged': False}
with open('visit.json', 'w') as handle:
 json.dump(visit, handle)
with open('visit.json') as handle:
 restored = json.load(handle)
print(restored['patient'])
print(type(restored['readings']).__name__)
print(json.dumps(restored['discharged']))

Output.``output Bob list false ``

Reasoning, JSON stores booleans in lowercase text and restores them as Python booleans; a tuple would become a list.

关键提醒。

Text modes control creation, truncation, and appending; JSON preserves portable data but not Python tuples.

10. Retrieval practice

Use this new task without looking back, lab = {'sample': 'A17', 'value': 38.4} must survive after the program ends. Give the exact JSON calls and mode for saving and reloading, explain the write mode, and state the exact output of print(loaded['value']).

Give API names, mode, and exact output.

11. Mastery check

Apply files and JSON to reading = {'device': 'kitchen-1', 'readings': (36.9, 37.2), 'notes': 'fresh'}. Save it with readable JSON, reload it, print the restored readings and its type name, and state one literal that cannot survive unchanged.

Give calls, exact output, and the changed literal.

Practice this interactively

Free account · instant grading · spaced review that schedules itself.

Start this course for free