# Python: write, append and read a text file

Published: 2026-11-30

Rights: original
Source: https://kairos-2z6s.onrender.com/res/python-files-full-en
`open` with `with` reads or writes a file and closes it on exit; `w` truncates, `a` appends. Tested here: with closes the file on exit; w truncates and a appends.

Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.

(Test: 3 tests were run, TE-34-A, TE-34-B and TE-34-C. The expected non-zero exit is TE-34-C (exit status 1). Every row has a recorded log in the evidence archive. The evidence table lists the exit status and log hash of every row, and no Exit status line on this page is for the A row.)

### TE-34-A: with closes the file on exit; w truncates and a appends

Setup for this run, inside a throwaway directory (`mktemp -d`):

```bash
printf 'old\n' > f.txt
```

Command:

```bash
python3 -c "
with open('f.txt','w', encoding='utf-8') as f:
    f.write('new\n')
    print('inside', f.closed)
print('after', f.closed)
with open('f.txt','a', encoding='utf-8') as f:
    f.write('more\n')
print(open('f.txt', encoding='utf-8').read().strip().split(chr(10)))"
```

Recorded output:

```
inside False
after True
['new', 'more']
```

This run checks the exit status and records the output; it asserts no expected text.

### TE-34-B: a file read in a with block can be iterated line by line, and strip removes the newline

Setup for this run, inside a throwaway directory (`mktemp -d`):

```bash
printf 'a\nb\n' > f.txt
```

Command:

```bash
python3 -c "with open('f.txt', encoding='utf-8') as f: print([l.strip() for l in f])"
```

Recorded output:

```
['a', 'b']
```

Exit status: 0. This status and the output match what was written before the run.

### TE-34-C: expected non-zero exit: opening a file that does not exist raises FileNotFoundError

No setup needed: the command below creates what it uses in the throwaway folder.

Command:

```bash
python3 -c "open('nosuch.txt')"
```

Recorded output: none, standard output was empty.

Standard error from the same run:

```
Traceback (most recent call last):
  File "<string>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'nosuch.txt'
```

Exit status: 1. This status and the output match what was written before the run.

## Reading the recorded output

The first line, inside False, was printed while the file was still open in the with block, so f.closed was False. The second line, after True, was printed after the block ended, so f.closed was True. The last line is the list read back from f.txt: ['new', 'more']. The word old, which the setup wrote first, is not in it, so mode w replaced it, and the text more, written with mode a, comes after new.

TE-34-B: by the setup, f.txt holds the lines a and b. Iterating over the open file gave each line, and strip removed the newline, so the list is ['a', 'b']. TE-34-C: open('nosuch.txt') stopped with exit status 1. The last line of standard error is FileNotFoundError: [Errno 2] No such file or directory: 'nosuch.txt'.

## Limits

The example writes and reads UTF-8 with `encoding='utf-8'` on both sides. Other encodings, BOM handling and newline translation are not covered here.

## Source

- https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

## Evidence

- `TE-34-A`: with closes the file on exit; w truncates and a appends

- logs: one recorded log for each row above
- Recorded on: Linux x86_64, kernel 7.3.4; bash 5.1.16; git 2.34.1; python 3.10.12; findutils 4.8.0; grep 3.7; sed 4.8; gawk 5.1.0; tar 1.34; curl 7.81.0. Locale C.UTF-8, TZ=UTC.

## Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) |
|---|---|---|---|---|
| `TE-34-A` | with closes the file on exit; w truncates and a appends | 0 | PASS | `ce981a6e9fe7` |
| `TE-34-B` | a file read in a with block can be iterated line by line, and strip removes the newline | 0 | PASS | `d88a833af687` |
| `TE-34-C` | expected non-zero exit: opening a file that does not exist raises FileNotFoundError | 1 | PASS | `ec0356921928` |

Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.

## Related guides
- [Python try and except: handle an error on purpose](https://kairos-2z6s.onrender.com/res/python-try-except-full-en)
- [Python f-strings: expressions and format specs](https://kairos-2z6s.onrender.com/res/python-functions-fstrings-full-en)
- [Python enumerate, zip and range: loop with an index or two lists](https://kairos-2z6s.onrender.com/res/python-enumerate-zip-range-full-en)
- [Python Generators: produce values one at a time](https://kairos-2z6s.onrender.com/res/python-generators-full-en)
- [Python dict.get: read a key without KeyError](https://kairos-2z6s.onrender.com/res/python-dict-get-full-en)
