In this lesson we will study how to write to text file in Python, using the append mode and we will give some examples.
How to write to text file in Python – first example
In this first example we will use our address_book.txt file which already contains data and add new contacts.
For example, let’s assume that the file contains these contacts:
Name: cristina – Telephone: 3567
Name: luisa – Telephone: 34789
Let’s implement an algorithm that allows you to add new data using the write method:
f = open('address_book.txt', 'a')
name = input('Enter a new name:')
telephone = input('Enter telephone:')
f.write('Name:' + name + '- Telephone:' + telephone)
f.close()
We can also use the print function to write to the file, where we specify the file to write to which we previously opened with open:
f = open('address_book.txt', 'a')
name = input('Enter a new name:')
telephone = input('Enter telephone:')
print('Nome:' + name + ' - Telefono:' + telephone, file = f)
f.close()
How to write to text file in Python – second example
In this second example, manage multiple entries thanks to cyclic instructions.
For example, suppose you want to ask the user how many names you want to add to the file and consequently manage the inputs based on the answer given.
This is a possible implementation of the simple algorithm in which we use the for loop:
f = open('address_book.txt', 'a')
n_data = int(input('How much data do you want to insert ?:'))
for i in range(n_data):
name = input('Enter a new name:')
telephone = input('Enter telephone:')
f.write('\ nName:' + name + '- Telephone:' + telephone)
f.close()
How to write to text file in Python – third example
If we want to add more elements, we can also use an iterative instruction and terminate, for example, when clicking on a character of your choice.
Let’s say we want to enter some data and stop when we choose to type the character *.
Here is a possible implementation in which we use the while loop:
f = open('address_book.txt', 'a')
print('Insert new contacts in the address book, to finish insert * in the name')
name = input('Enter a new name:')
while name! = '*':
telephone = input('Enter telephone:')
f.write('\ nName:' + name + '- Telephone:' + telephone)
name = input('Enter a new name:')
f.close()
I take this opportunity to remember that the for loop is used when we know exactly how many times the loop will be executed, as in the second example where n_data will be executed. While the while loop is used when you want to stop the loop following a condition.
In this lesson we have seen some simple examples of how to add content to a file in Python.
Some useful links
Introduction to dictionaries in Python
Use Python dictionaries
Create dictionaries in Python
Python get() method
keys() method
items() method
pop() method
popitem() method
Sort dictionary in Python