Apr. 24, 2013

With statement in Python

Overview

In Python you need to give access to a file by opening it. You can do it by using
the open() function. Open returns a file object, which has methods and attributes
for getting information about and manipulating the opened file. 

With statement

With the "With" statement, you get better syntax and exceptions handling. 

"The with statement simplifies exception handling by encapsulating common
preparation and cleanup tasks."

In addition, it will automatically close the file. The with statement provides
a way for ensuring that a clean-up is always used.
Without the with statement, we would write something like this:
file = open("welcome.txt")

data = file.read()

print data

file.close()  # It's important to close the file when you're done with it

With Statement Usage

Opening a file using with is as simple as: with open(filename) as file:
with open("welcome.txt") as file: # Use file to refer to the file object

   data = file.read()

   do something with data
Opens output.txt in write mode
with open('output.txt', 'w') as file:  # Use file to refer to the file object

    file.write('Hi there!')

Notice, that we didn't have to write "file.close()". That will automatically be
called. 

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.