How do you read and write a file safely?

Python errors and files · Freshers

Model answer

Use a with block, which closes the file automatically: with open("data.txt", encoding="utf-8") as f: text = f.read(). Use mode "w" to write (overwrites) or "a" to append. Always specify the encoding, and pathlib.Path makes paths easier.

Learn this topic

Handling Errors in Python: try, except, finally and raise in the course Python for Beginners: Learn to Code with Real Projects.

Sign in to add your own answer.

More questions