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.
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.
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
- How to use the Python for loop
- How to use Python Sets
- How to use a Python Dictionary
- How to use Python Classes
- How to use Python Range
- How to use Python if-else statements
- How to use Python RegEx
- How to use Python Lists
- How to use Python Enumerate
- How to use Python Functions
- How to use Python Split
- How to use Python Try-Except
- How to use Python Tuples
- How to use Python Arrays
- How to use Python Sort
- How to use the Python DateTime
- How to download Python?
- How to use the Python FileWrite function
- How to use Python Lambda
- How to use Python ListAppend
- How to use Python ListComprehension
- How to use Python Map
- How to use Python Operators
- How to use Python Pandas
- How to use Python Requests
- How to use Python Strings
- How to use Python Count
- How to use Python Comments
- How to use the Python File Reader method
- How to use the Python IDE-s
- How to use Python logging
- How to use Python Print
- How to use the Python Zip
- How to use Python Append
- How to use Python Global Variables
- How to use the Python join method
- How to use Python list length
- How to use Python JSON files
- How to use Python Modulo
- How to use Python file opening methods
- How to use Python round
- How to use Python sleep
- How to use Python replace
- How to use Python strip
- How to use the Python Time module
- How to use Python unittests
- How to save data to a text file using Context Manager?
- How to use Python external modules
- How to use Python find
- How to use the Python pip package manager
- How to delete files in Python
- Parsing XML files in Python
- How to make a GUI in Python
- How to use Python in Command Prompt
- How to Run a Python Program in VS Code
- How to run a program in Python IDLE
- How to run a program in Jupyter Notebook
- How to read a text file in Python
- How to add numbers in Python
- How to ask for user input in Python
- How to debug in Python
- How to create a thread in Python
- How to import a library in Python
- How to use the PIP package manager
- How to use classes in Python
- How to reverse strings in Python
- How to convert a string to int in Python
- How to print on the same line in Python
- How to remove items from a list
- How to add to a dictionary in Python
- How to raise an exception in Python
- How to throw an exception in Python
- How to stop a program in Python
- How to use Python assert
- How to use the Python compiler
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.
