|
| 1 | +# with open('example.txt', 'a') as file: |
| 2 | +# text = file.write('\nHappy birthday') |
| 3 | +# print(text) |
| 4 | + |
| 5 | + |
| 6 | +#older approach |
| 7 | +# file = open('example2.txt', 'w') |
| 8 | +# text = file.write('Legacy Method') |
| 9 | +# print(text) |
| 10 | +# file.close() |
| 11 | + |
| 12 | +# with open('colors.txt') as file: |
| 13 | +# # colors= file.read() |
| 14 | + |
| 15 | +# # chaining the split(), returns list |
| 16 | +# colors = file.read().split() #['red', 'blue] |
| 17 | + |
| 18 | +# for color in colors: |
| 19 | +# print(color) |
| 20 | + |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | + |
| 25 | +#identify colors that have more than 4 chars |
| 26 | +# with open('colors.txt') as file: |
| 27 | +# colors = file.read().split(', ') |
| 28 | + |
| 29 | +# with open('colors4.txt', 'w') as file4: |
| 30 | +# for color in colors: |
| 31 | +# if len(color)>4: |
| 32 | +# file4.write(color + '\n') |
| 33 | + |
| 34 | +# import datetime |
| 35 | + |
| 36 | +# #Read file |
| 37 | +# start = datetime.datetime.now() |
| 38 | +# with open('phonebook.txt') as file: |
| 39 | +# phone_book = file.read() |
| 40 | +# end = datetime.datetime.now() |
| 41 | + |
| 42 | +# print(f'Your file loaded in {end-start}') |
| 43 | + |
| 44 | +with open('phonebook.txt') as file: |
| 45 | + phone_book = file.read() |
| 46 | + |
| 47 | + phone_book = phone_book.split('\n') |
| 48 | + name = input('Lookup name: ') |
| 49 | + |
| 50 | + found_entry = False |
| 51 | + for entry in phone_book: |
| 52 | + # if name in entry: #Tomas --> Tom |
| 53 | + if name.lower() in entry.lower(): |
| 54 | + print(entry) |
| 55 | + found_entry = True |
| 56 | + |
| 57 | + if not found_entry: |
| 58 | + print('Contact not found') |
| 59 | + name = input('Enter new contact name: ') |
| 60 | + phone_number = input(f'Enter the number for: {name}') |
| 61 | + |
| 62 | + phone_book.append(name + " " + phone_number) |
| 63 | + |
| 64 | + phone_book.sort() |
| 65 | + with open('phonebook2.txt', 'w') as file2: |
| 66 | + file2.write('\n'.join(phone_book)) |
| 67 | + |
| 68 | +# print(type(phone_book)) |
| 69 | +# print(phone_book) |
0 commit comments