Created
November 25, 2018 21:13
-
-
Save Ojha-Shashikant/db1979e810d2402da6ced2dbb313ef1d to your computer and use it in GitHub Desktop.
Writing contacts to file, reading contacts from file and printing in ascending order of names.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' Writing contacts to file, reading contacts from file and printing in ascending order of names ''' | |
def creating_file(): | |
FH = open("C:\\Users\\Ojha\\Documents\\Python exercises\\Python Scripts\\Contact_list.txt", 'w') | |
return FH | |
def name_input(): | |
name = input("Provide contact person name: ") | |
final_name = name.capitalize() | |
return final_name | |
def contact_number_input(): | |
return input("Provide contact number: ") | |
def write_contacts_to_file(FH): | |
contacts = dict() | |
name = name_input() | |
while name != '': | |
contact_number = int(contact_number_input()) | |
contacts[name] = contact_number | |
name = name_input() | |
for name, contact_number in contacts.items(): | |
FH.write(name + ':' + str(contact_number) + '\n') | |
FH.close() | |
def reading_from_file(): | |
with open("C:\\Users\\Ojha\\Documents\\Python exercises\\Python Scripts\\Contact_list.txt", 'r') as FH: | |
text = FH.read() | |
details = text.split() | |
contacts = dict() | |
for detail in details: | |
item = detail.split(':') | |
contacts[item[0]] = int(item[1]) | |
return contacts | |
def printing(contacts): | |
all_names = contacts.keys() | |
sorted_names = sorted(all_names) | |
for name in sorted_names: | |
print(name + ':' + str(contacts[name])) | |
# main starts here | |
if __name__ == '__main__': | |
FH = creating_file() | |
write_contacts_to_file(FH) | |
contacts = reading_from_file() | |
printing(contacts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment