Menu
Coddy logo textTech

With a File

Lesson 12 of 28 in Coddy's Clean Code - Write better code using Python course.

Python use special reserved word when dealing with files: <strong>with</strong>.

When using - with open syntax the file you open will automatically close for you when you exit the with block.

with open('file.txt') as f:
    content = f.read()
    ...

The with statement is better because it will ensure you always close the file, even if an exception is raised inside the with block

Try it yourself

This lesson doesn't include a code challenge.

All lessons in Clean Code - Write better code using Python