Basic Programming in Python - Part 5
Reading and Writing in Files using Python
We use files in daily life. There are different formats of files, in which information is stored in organizations or individuals. Python provides us the power to create, update or remove files and file contents. As you get going, you will enjoy playing with files using python. So, without any further delay, let us get started with files.
There are a few modes in which you can open a file and do operations. I will list all the modes and their use cases below. However, let us first see, how we can read the contents of a file.
In the above code snippet, we are initially opening a file named funtalk.txt and holding its reference in variable 'f'. Python files can be read using the read() method. Hence, we are printing as we are reading in the second line. In the end, we are closing the file using the close() method. We must remember to close the file which lets the program free up the memory space that was allocated to hold the file. Here, we did not specify the path of the file, as the file exists in the same directory as the notebook. The default mode is read mode and hence the above code snippet has opened funtalk.txt in "read" mode.
Now, let's say we want to write some content into a file, and we open the file in write mode. Look at the screen below.
Please find the below screenshot from my file explorer.
And here's the screenshot of contents in the new file:
From the above code-snippet, as the program did not find a file with the name passion.txt, python has created a new file and put the content in it. If the file already exists, it would override the content in it with new ones.
We could read this file in our python program and find out words with maximum occurrence. Will update the blog soon.
Thanks!