Are you reading/writing files the right way❓

File operations like reading, writing or appending are very common.

In Python, we can do it pretty easily just by calling the Open() function on it and then iterating through the file.:bulb:

The 2nd argument in open() defines the type of operation - r for read, w for write and a for append.

However, once you have reached the end of the file you would also need to close it to free up resources.

This is done using the Close() function.

But what if an error occurred while processing the file? File will not be closed and your code will be doomed.:unamused:

To keep this from happening we can put the same functions inside try & finally blocks, which is Python’s way of handling exceptions.

So even if an error occurred, it will still close the file during the finally block.

But there’s an even better way to do this - using “with” and "as’.:zap:

Using with and as, Python automatically closes the file when the read/write operation is completed.

You don’t need to explicitly close the file even if there is an error during the processing.

Using this method you are always secured that the operation will be performed correctly and file will be closed.:rocket:

These are also known as Context Managers in Python!

Isn’t this handy?

#python #datascience