← Python Programming
Files, errors and data · 15 MIN

Reading and writing text files

Reading and writing text files

Use open with a context manager so files are closed reliably. Specify an encoding such as UTF-8. Read text with read or iterate over lines; write text with write. Be careful not to overwrite important files accidentally.

Try it yourself

Change the example, run it, and explain the result in your own words. Then create one variation of your own.

Key idea

Use the example as a starting point, not something to memorize. Practise, inspect the result and make small improvements.

Code example

with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("Keep practising Python\n")

with open("notes.txt", encoding="utf-8") as file:
    print(file.read())