---
title: "With Statements Got Better With Python 3.1"
description: "In my previous post about using the with statement in python /me had tried to throw some light on why to use ’with’ in JS."
url: "https://h3manth.com/scribe/statements-got-better-python-31/"
canonical_url: "https://h3manth.com/scribe/statements-got-better-python-31/"
markdown_url: "https://h3manth.com/scribe/blog/statements-got-better-python-31.md"
publishDate: "2012-07-24T00:00:00.000Z"
author: "Hemanth HM"
category: "python"
tags: ["python","web"]
word_count: 183
reading_time_minutes: 1
x_markdown_tokens: 371
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# With Statements Got Better With Python 3.1

> In my previous post about using the with statement in python /me had tried to throw some light on why to use ’with’ in JS.

In my previous post about [using the with statement in python](http://h3manth.com/content/with-statement-python) /me had tried to throw some light on why to use 'with' statements and the fun of using them.

Had also mentioned about, the `contextlib` module for python 2.7+ but with 3.X 'with statements' were better and the fun multiplied!

Let's see a small example on why 'with' has become better with python 3.1

> > > with open('site.log') as infile, open('err.log', 'w') as outfile: ... for line in infile: ... if 'ERROR' in line: ... outfile.write(line) 

**Mind == BLOWN**

It's so easy to handle multiple files with 'with statements' in python 3.1! Not that it's only in this version, but 3.X series has a better potential, is what is been alluded here.

Basically the only difference is that Python's with operates over a context management protocol involving some `__magic__` methods so it can work with other things in addition to files.

**Update 0 :** 2.7 supports multiple context managers too! Despite the numbering, 2.7 was released a year after 3.1. It added a bunch of features that helped compatibility with 3.x.
