he open() function writes contents to an existing file. You must use the “w”, “a”, “r+”, “a+’, or “x” file modes to write text to a file. The most common file modes are “w” and “a”. These modes write data to a file and append data to a file, respectively.
Do you need to make a change to a file? Python has you covered. You can write data to a new file or modify existing data in a file using Python’s built-in I/O functions.
In this guide, we’re going to discuss how to write to a file in Python. We’ll walk through an example to illustrate how to write to a file. Let’s get started!
How to Write to a File in Python
You can write to a file in Python using the open() function. You must specify either “w” or “a” as a parameter to write to a file. “w” overwrites the existing content of a file. “a” appends content to a file.
In Python, you can write to both text and binary files. For this tutorial, we’re going to focus on text files. These are files without any specific encoding, and so they can be opened using a text editor. Text files include .csv files, .txt files, and .md files.
There’s no need to import any external library to write to a file in Python. The Python programming language has a built-in suite of tools you can use to write to a file.
Open a File for Writing
Before we can write to a file, we need to learn how to open one. Let’s say that we want to write a list of ingredients for a scone into a list. We’d start by opening up a file called scone.txt like this:
scone_file = open(“scone.txt”, “w”)
We’ve opened our scone.txt file using the w mode. This means that we can write to the file with which we are working. There are a couple of different modes that you may want to use. The ones we need for writing are:
- w: This mode allows you to write to a file. It erases the contents of a file and creates a new one.
- a: This mode appends information to the end of a file.
- r+: This mode allows you to read information from and write data to a file.
- a+: This mode allows you to add information to the end of a file and read the file.
- x: Creates a file if one does not already exist to which we can add data.
When you open a file in Python, you need to close it afterward. Otherwise, Python will automatically close and delete the file. The best way to do close the file you are working with automatically is by using a with statement:
with open("scone.txt", "w") as file: // Work with the file
Python Write to a File
We want to start adding the ingredients for our scone to our file. To do so, we can use the write() function. This adds the characters you specify to the end of a file.
When you create a new file object, a new file will be created if one does not already exist. We’re going to use the “w” mode to write to our scones.txt file because it does not currently include any information.
Let’s add three ingredients to our scones.txt file:
with open("scone.txt", "w") as file: file.write("350g self-raising flour\n") file.write("1 tsp baking powder\n") file.write("85g butter\n")
When this code executes, three lines of text are added to scone.txt. We’ve used “\n” characters at the end of each line to indicate that we want new lines to appear in our text. These are called newline characters and print a line to the file.
If we don’t specify these characters, our text would all be written on the same line.
Let’s open our scones.txt file:
350g self-raising flour
1 tsp baking powder
85g butter
Our file has three lines of text! Now, we’ve got a few more ingredients to add. To add them, we’re going to open our file in append mode.
If we opened up our file in write mode, a new file would be created. We would lose the ingredients we already added to the file. Let’s open the file:
with open("scone.txt", "a") as file: file.write("3 tbsp caster sugar\n") file.write("175ml milk\n") file.write("1 tsp vanilla extract\n")
This code adds three files of text to scones.txt:
350g self-raising flour
1 tsp baking powder
85g butter
3 tbsp caster sugar
175ml milk
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
1 tsp vanilla extract
We did it! We’ve added text to a text file in Python.
Python Write to an Existing File
You can write to an existing file using the open() function and the “a” parameter. You can only write to the end of a file.
This means that there’s no way for you to edit an existing file using only the built-in Python file operations. There is a workaround that we can create. This involves reading a file into a list and then manipulating the contents of the list.
There is no limit to the number of characters you can read and write to files in Python. You can only write string data to a file. You cannot write integers, floating-points, or other data types to a file.
Let’s say that we want to add “Scone Ingredients” to the top of our ingredients list. We could do this by reading our ingredients into a list and then inserting our new line of text at the start using insert().
Prepare a List to Write to a File
The insert() function accepts two parameters. You must first specify the index position at which you want to insert an item. Then, you must specify the value you want to insert into the list. Consider this code:
with open("scones.txt", "r") as file: scone_file = file.readlines() scone_file.insert(0, "Scone Ingredients\n") with open("scones.txt", "w") as scones: contents = "".join(scone_file) scones.write(contents)
We’ve started by opening our file in “read” mode. We use the readlines() function to retrieve all the contents of our existing file. This returns a list of the lines in our file. We use the insert() function to add “Scone Ingredients\n” to the index position 0 in our list of file lines.
Python Write to Text File
Once we’ve added the text we want to add, we write all the contents to the file. We use the .join() function to convert our list of file lines to a string. We then write that value to the file.
Let’s open up our scone.txt file data:
Scone Ingredients
350g self-raising flour
1 tsp baking powder
85g butter
3 tbsp caster sugar
175ml milk
1 tsp vanilla extract
Our list now starts with “Scone Ingredients”.
Similarly, we can edit the contents of our list of file lines. Let’s say that we want to increase the quantity of butter in our recipe to 95g. We could do so using this code:
with open("scones.txt", "r") as file: scone_file = file.readlines() scone_file[3] = "95g butter\n" with open("scones.txt", "w") as scones: contents = "".join(scone_file) scones.write(contents)
We have used square bracket notation to change the value of the item at index position 3 in our list of ingredients. This item corresponds to our “butter” ingredient.
We set the value at this position in the list to “95g” of butter. We then write the revised contents of the file back to the file in write mode. Our code returns:
Scone Ingredients
350g self-raising flour
1 tsp baking powder
95g butter
3 tbsp caster sugar
175ml milk
1 tsp vanilla extract
Our recipe now calls for “95g butter” instead of “85g butter”.
Conclusion
You can read data from and write data to a file using the open() method. The two main modes that you’ll use to write to a file are “a” and “w”, which stand for “append” and “write”, respectively.
To learn more about Python, read our complete guide on how to code in Python.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.