Menu

File Handling

Common file handling errors

File handling goes wrong in a few predictable ways. Knowing what each mistake does to your data helps you spot it when a program behaves oddly.

Losing data or wiping it

If you never call .close() on the file object, written data may not be saved properly to secondary storage. Close the file as soon as you have finished with it, after the last read or write.

Opening an existing file in write mode ("w") empties it first, and creating a missing file with "w" makes a new empty one. If you open diary.txt with "w" to write today's entry, every earlier entry is gone. Use "r" when you want to keep and read the existing contents.

Mistakes when writing

.write() puts exactly the characters you give it and nothing else. Without \n at the end, the next value lands on the same line, so writing "4" then "7" stores "47" and it reads back as one value. .write() also only accepts a string, so a number must be wrapped in str() first.

Mistakes when reading

A line read from a file usually comes back with its newline still attached, so .strip() is needed before comparing it or printing it neatly. The text is also a string: "7" * 2 gives "77" rather than 14, so cast with int() or float() before any arithmetic or number comparison.

A loop only moves on when it calls .readline() again inside the loop body. Forget that and the same line is used every time, so the result is wrong โ€” or the loop never ends.

Practise this