We have learned how to open and read a file in python in Python File Read lesson. In this lesson, we will focus another action that we will use with files. This is “write”. In this lesson, we will learn Python File Write with different examples.
As we have learned before, we use python open function to work with files, for file handling. With open() function, we use two different parameters. One of them is the file that we will work and the other one is the method that we will use. These methods are given below:
For Python File Write mode, we will use “w” as the second parameter of open() function in python. With the help of this function and this parameter, we will able to modify and overwrite existing files after opening them.
Beside “w” parameter, we can also use “a” parameter to append files. In other words, with “a” parameter, we can add new characters at the end of the files.
Let’s shows this with examples. Again, think about that, we have a demo file under the same folder with python. The name of this file is fileabc.txt and the content of this file is:
Weak people revenge.
Strong people forgive.
Intelligent people ignore.
Firstly, let’s check the content with open function and read method. After that we will close it.
The output will be:
You can also watch the video of this python lesson!
Now, let’s use append mode to add new characters to this file. Here, we will add “A Perfect Quote!” sentence, at the end of this demo file. To do this, we will use open() function, “a” mode and write() method. After this modification, we will also use open function with read mode and read() method together to read the new content.
With this Python File Write code, the new content of this demo file will be like below:
We have learned how to add new characters at the end of a file. Now, let’s learn how to modify or completely change the entire content. To do this we will use open function and “w” mode together.
Here, we will use the same demo file as above. We will change the entire content of this file with the below quote of Leonardo Da Vinci:
Simplicity is the Ultimate Sophistication.
To do this, we will use the below code. Firstly, we will open the file with “w” mode and modify the file with write() method. Then close. After that, we will open it again to read.
The output of this Python File Write code and the content of the demo file will be like below:
In this lesson, we have learned how to write and modify an existing file with Python File Write modes. These modes are append (a) and write (w) modes. You will use these methods in your coding activities too much.