How to Read and Write a File in Python ?

A quick guide to file operations in python

Bijen Adhikari
3 min readMay 2, 2022

--

source: https://logos-world.net/python-logo/

Open/ Close

The syntax for opening a file operation is :

There are two operations associated with file. We use open to create a file descriptor. Then we have to close the file to prevent memory leakage.

But closing the file manually is tedious process. And prone to error.

In the above example the file is opened but never closed. Because once the exception happens, the program will exit.

In the above code, we can guarantee the file will be closed even if the code runs successfully or an exception happens. But the above code has too many boilerplate. Python supports a better syntax called context manager.

After the intended block python will call fd.close() automatically

Write

This command opens a file for writing. Let’s learn what it does by few short snippets.

--

--

Bijen Adhikari

Hi, I am Bijen from Nepal I write about Electronics, Electrical, Programming, Fitness. Also, I am a certified SSI Master Trainer.