How to save data to a text file using Context Manager

  • Reading time:16 mins read

What is a Context Manager used for?

Using the context manager to save data to a text file, or manage file operations or database connections is considered the best practice in Python.

When dealing with files in Python the context manager allows us to easily open and automatically close files thereby avoiding system slow down.

 

 

Now to get started with using the context manager we need two keywords ‘with open’ followed by a pair of parentheses. Once we have opened the parentheses we need to pass two arguments that will be separated by a comma.

The first argument is the name of the file that we’re going to open followed by the mode that we want the file opened.

How to save data to a text file with the help of a context manager?

In this article, we are going to open files in write mode that is abbreviated by ‘w’ and append mode that is abbreviated by the letter  ‘a’.

Now if the file we are opening already exists the context manager will open it for us. On the other hand, if the file does not exist the context manager will go ahead and create the file.

 

save data to a text file

 

Let’s try to open a file named ‘data.txt’ in write mode which is abbreviated by the letter ‘w’. We then need to open it as variable f which is the conventionally used way.

And now since we have access to that file we can do f.write() in the subsequent indented line.

Now whatever string or character that we put in between the parentheses of f.write(), is going to be written in our text file ‘data.txt’ since we have opened the file in write mode.

Opening Files in Write Mode

Suppose we write the word ‘codeberry’, within the parentheses and run the python file. We are going to have the word ‘codeberry’ written to the text file ‘data.txt’ as shown below.

 

 

Now if we change the word from ‘codeberry’ to ‘elephant’ we will notice that instead of adding the word to the file, the word ‘codeberry’ is overwritten by the new word ‘elephant ’ as shown below.

 

Opening Files in Append Mode

Opening files in Append mode on the other hand allows us to add new text at the end of the file. To open a file in append mode we simply need to change the letter ‘w’ to ‘a’ which stands for appending mode.

 

save data to a text file

 

We also need to add a new string that will be appended to the file ‘data.txt’ alongside a new line character that will ensure that the string is added to a new line instead of at the end of the current string which is animal.

 

 

If we add another string say ‘tiger’ and re-run the code again the string is also going to be appended to the file ‘data.txt’ on a new line as shown below.

 

 

Now suppose we wanted to add a different data type to this file, in this case, we need to convert it to a string first. This is because ‘f.write()’ only takes a string.

For example, if we try to add an integer number for example 15, we’d get an error.

 

 

Now the easiest way to avoid this error is by wrapping the integer in ‘int()’, this will turn the integer 15 into a string which will then allow us to add it as a string to the file data.txt.

We also need to include the newline character so that the file appears on a new line.

 

Summary

It is important to keep in mind that creating a file in write mode will overwrite the file every time.

On the other hand, if you use the append mode and a new line character, creating a new file will not overwrite the pre-existing one.

If you’d like to see more programming tutorials, check out our Youtube channel, where we have plenty of Python video tutorials in English.

In our Python Programming Tutorials series, you’ll find useful materials which will help you improve your programming skills and speed up the learning process.

Programming tutorials

Would you like to learn how to code, online? Come and try our first 25 lessons for free at the CodeBerry Programming School.

Learn to code and change your career!

100% ONLINE

IDEAL FOR BEGINNERS

SUPPORTIVE COMMUNITY

SELF-PACED LEARNING

Not sure if programming is for you? With CodeBerry you’ll like it.