Reading and writing to files is a very important part of many Python programs. We have already seen how to read from a file in Python. This blogpost shows you three easy steps to writing a file in Python.
First, let us open a file called “friends.txt” using the open() method as shown below:
The second argument, i.e., “w” is called the mode and here it indicates that you are opening this file with the intent to write into the file. Recall, from the Python read from a file blogpost, when we use “r” as the second argument we intend to read from the file. There is also an append mode (“a”) where you do not plan to overwrite any existing contents of the file but simply append to the contents (i.e., writing after the current last line of the file).
If you run the program as shown above you will see that it would have created a new file called “friends.txt” in your current working directory.
Also recall that it is best practice to close the file handle when done so we will usually have our program structure as follows:
We are now ready to start writing to the file!
How to write to a file in Python
Let us now do:
If you now open your friends.txt file, you will see:
What has happened? The program has indeed written the two names but note that there is no line space separating them. You will need to issue an explicit carriage return or newline, like so:
This will make the friends.txt file look like:
Reading and Writing to Files in the same Python program
Let us write a Python program to read two numbers from a file and then print their sum at the end of the file. We create a file called “numbers.txt” containing two numbers like so:
Now let us write a program to read these two lines and print their sum onto the screen. (Then we will determine how to append the sum to the end of the file). Here is our first attempt:
This is not quite what we were expecting. Note that by default readline() reads one line from a file as a string (including the newline character at the end of the line). Second, the “+” in the print above is really doing string concatenation, not integer addition. We will need to do some typecasting, like so:
This produces as expected:
Now we need to determine a way to write this back to the file. Since we opened the file in read mode, we cannot write to the file in the current condition. For instance, if you try:
We get the error:
Looks like we will need to convert it to a string in order to write to the file. Let us try casting the sum back to a string:
Now we get the error:
So we need to close the file and reopen it in append mode.
This works! Let us open the numbers.txt file and see what it contains.
Note that this is because the file did not contain an ending newline character. To be safe, you can update your program as follows:
This produces the intended result in numbers.txt:
Note that the second write line adds its own newline character as we learnt earlier.
More about file modes in Python
What will happen if we update the above program like:
You will see that the file numbers.txt contains:
It has overwritten the file! The difference between opening files in append mode (“a”) versus the write mode (“w”) is that in the append mode, the file pointer is positioned at the end of the file whereas in the write mode, it is positioned at the beginning of the file. As a result any write commands will overwrite the existing content in the file.
In this blogpost, you have learnt how to open a file for writing and adding or updating contents of the file. It is good programming practice to specify the full pathname of the file and also trap for exceptions.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.