In Python, you can access a file by using the open() method. However, using the open() method directly requires you to use the close() method to close the file explicitly. Instead, you can create a context using the with Open statement in python. It returns a file object, which has methods and attributes for getting information about and manipulating the opened file.
The With Statement in Python
With the “With” statement, you get better syntax and exception 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
In the above code, we need to close the file explicitly using the close() method.
With Statement Usage with Open() Function in Python
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!')
In the above code, you can observe that we have opened the output.txt file using the with open statement. The statement returns a file pointer that is assigned to the variable “file”. Now, we can perform any operation on the file object inside the context of the with statement. Once all the statements are executed and the execution reaches the end of the with context block, the file is automatically closed by the python interpreter. Also, if the program runs into any exception inside the with block, the with open context in python closes the file before terminating the program. In this way the data inside the file remains safe even if the program is terminated abruptly.
Notice, that we didn’t have to write “file.close()”. That will automatically be called.
In this article, we have discussed how you can use the with open statement instead of the open()
method to open a file in python. To learn more about python programming, you can read this article on string manipulation in Python. You might also like this article on python if else shorthand.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.