Learn / Python / File Handling

Intermediate 12 min

File Handling

Read and write text files safely with context managers.

What you will learn

  • Use with open()
  • Read and write text
  • Handle missing files
python
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")

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

Try it yourself

Write a function that counts lines in a file path.