Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Regular Expressions in Python Introduction to Regular Expressions Reading Files

what's the difference in 'with' and '.open()'

Please see the video first before giving the answer so you can easily understand what i want to ask. In teachers note there is written that if we use "with" it causes the file to automatically close once the action inside of it finishes. So why we need to use it, to close file automatically.i can also do it by using open().for example:

names=open("names.txt")
data=names.read()
names.close()

so what difference this code made

with open("names.txt") as names:
  data=names.read()

please explain me briefly about it type everything what you know about it

2 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

The with gives you a context that'll end automatically and close the connection without you having to close it yourself. It's generally a better thing to use as it prevents you from forgetting and leaving lots of open connections sitting around.

Good question! They do the exact thing. I usually use "with" way, but when I'm dealing with LOTS of code, I use the open/closing method.