1. Reading a file

Use a context manager to handle file resources safely.

The with block ties acquisition and release together so the lifetime of the file handle is obvious from indentation alone. That improves correctness first, and it also makes the code easier to modify later without forgetting cleanup.

1.1. Don’t do this

1f = open('README.md')
2try:
3    data = f.read()
4    print(len(data))
5finally:
6    f.close()

1.2. Do this

1with open('README.md') as f:
2    data = f.read()
3    print(len(data))