Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

Writing to a File in Python

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:

f = open("friends.txt","w")

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:

f = open("friends.txt","w")
# write something here
f.close()

We are now ready to start writing to the file!

How to write to a file in Python

Python Write File

Let us now do:

f = open("friends.txt","w")
f.write("Adam")
f.write("Emily")
f.close()

If you now open your friends.txt file, you will see:

AdamEmily

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:

f = open("friends.txt","w")
f.write("Adam\\n")
f.write("Emily")
f.close()

This will make the friends.txt file look like:

Adam
Emily

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:

3
4

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:

f = open("numbers.txt","r")
num1 = f.readline()
num2 = f.readline()
print(num1+num2)
f.close()

This produces:

3
4

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:

f = open("numbers.txt","r")
num1 = f.readline()
num2 = f.readline()
print(int(num1)+int(num2))
f.close()

This produces as expected:

7

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:

f = open("numbers.txt","r")
num1 = f.readline()
num2 = f.readline()
f.write(int(num1)+int(num2))
f.close()

We get the error:

Traceback (most recent call last):
File "main.py", line 4, in <module>
  f.write(int(num1)+int(num2))
TypeError: write() argument must be str, not int

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:

f = open("numbers.txt","r")
num1 = f.readline()
num2 = f.readline()
f.write(str(int(num1)+int(num2)))
f.close()

Now we get the error:

Traceback (most recent call last):
File "main.py", line 4, in <module>
  f.write(str(int(num1)+int(num2)))
io.UnsupportedOperation: not writable

So we need to close the file and reopen it in append mode.

f = open("numbers.txt","r")
num1 = f.readline()
num2 = f.readline()
f.close()
  
f = open("numbers.txt","a")
f.write(str(int(num1)+int(num2)))
f.close()

This works! Let us open the numbers.txt file and see what it contains.

3
47

Note that this is because the file did not contain an ending newline character. To be safe, you can update your program as follows:

f = open("numbers.txt","r")
num1 = f.readline()
num2 = f.readline()
f.close()
  
f = open("numbers.txt","a")
f.write('\n')
f.write(str(int(num1)+int(num2)))
f.close()

This produces the intended result in numbers.txt:

3
4
7

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:

f = open("numbers.txt","r")
num1 = f.readline()
num2 = f.readline()
f.close()
  
f = open("numbers.txt","w")
f.write('\n')
f.write(str(int(num1)+int(num2)))
f.close()

You will see that the file numbers.txt contains:

7

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.

Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

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.

Copyright @ Kodeclik 2024. All rights reserved.