Mastering Python for Networking and Security
上QQ阅读APP看书,第一时间看更新

With a Context Manager

There are multiple ways to create files in Python, but the cleanest way to do this is by using the with keyword, in this case we are using the Context Manager Approach.

Initially, Python provided the open statement to open files. When we are using the open statement, Python delegates into the developer the responsibility to close the file when it's no longer need to use it. This practice lead to errors since developers sometimes forgot to close it. Since Python 2.5, developers can use the with statement to handle this situation safely. The with statement automatically closes the file even if an exception is raised.

The with command allows many operations on a file:

>>> with open("somefile.txt", "r") as file:
>>> for line in file:
>>> print line

In this way, we have the advantage: the file is closed automatically and we don’t need to call the close() method.

You can find the below code in the filename create_file.py

def main():
with open('test.txt', 'w') as file:
file.write("this is a test file")

if __name__ == '__main__':
main()

The previous script uses the context manager to open a file and returns this as a file object. Within this block,  we then call file.write ("this is a test file"), which writes it to our created file. In this case, the with statement then handles closing the file for us and we don’t have to worry about it.

For more information about the with statement, you can check out the official documentation at  https://docs.python.org/2/reference/compound_stmts.html#the-with-statement.