In this lesson we will deepen the Python write() method and in particular we will store input data in text files in Python. We will create a simple address book that contains the names and phones of our friends.
First example on Python writes()
Let’s take a first example by storing one input data at a time in the address book.txt file.
First we create the object in order to then use the methods and properties of the files:
f = open(“address_book.txt”, ‘w’)
So let’s print a sentence on the screen to say that we are memorizing the names and phones of our friends:
print (‘Enter the names and phone numbers of your friends!’)
After we ask you to enter the name of our friend:
name = input(‘Name:’)
Then we ask to insert the telephone:
telephone = input(‘Telephone:’)
We use the Python write() method to insert the data taken as input:
f.write(‘Name:’ + name + ‘- Telephone:’ + telephone)
Finally we close the file to be able to see the data stored in the mass memory:
f.close()
We remind you that if we forget to carry out this last operation, we may not see some or all of the records entered during the writing phase.
Second example on Python write()
In the first example we stored only one piece of data in Python, now we will use a loop to store more input data.
Suppose we want to stop entering data when we insert the asterisk character.
We could use a while loop, so that as long as the name is different from the asterisk character, it will keep asking for data.
Here is a possible implementation of the program:
f = open("address_book.txt", 'w')
print('Enter the names and phone numbers of your friends! Assign the character * to the name when you want to stop entering')
name = input('Name:')
while name! = '*':
phone = input('Phone:')
f.write('Name:' + name + '- Phone:' + phone + '\ n')
name = input('Name:')
f.close()
In this lesson we have created a simple address book in Python using write() method.
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