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
withstatement is better because it will ensure you always close the file, even if an exception is raised inside thewithblock
Try it yourself
This lesson doesn't include a code challenge.
All lessons in Clean Code - Write better code using Python
4Pythonic Code
The ZenVariable TricksDealing With ListsWith a FileAccess a Dictionary ElementEquals Operations