Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotes.py
More file actions
Latest commit
208 lines (151 loc) · 5.74 KB
/
Copy pathNotes.py
File metadata and controls
208 lines (151 loc) · 5.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env python3
"""
Simple note manager with CRUD operations and search functionality.
"""
importos
NOTES_FILE="notes.txt"
defclear_console():
"""Очищает консоль."""
os.system("cls"ifos.name=="nt"else"clear")
defwait_for_enter():
"""Ожидает нажатия Enter и очищает консоль."""
input("\nДля выхода в меню нажмите Enter...")
clear_console()
definit_notes_file():
"""Создаёт файл для заметок, если он не существует."""
ifnotos.path.exists(NOTES_FILE):
withopen(NOTES_FILE, "w", encoding="utf-8") asf:
f.write("")
defload_notes():
"""Загружает все заметки из файла, игнорируя пустые строки."""
try:
withopen(NOTES_FILE, "r", encoding="utf-8") asf:
lines= [lineforlineinf.readlines() ifline.strip()]
returnlines
exceptFileNotFoundError:
return []
exceptExceptionase:
print(f"Ошибка чтения: {e}")
return []
defsave_notes(lines):
"""Сохраняет заметки в файл."""
iflinesisNone:
lines= []
withopen(NOTES_FILE, "w", encoding="utf-8") asf:
f.writelines(lines)
defdisplay_notes(lines, show_header=True):
"""Отображает список заметок с нумерацией."""
ifshow_header:
print("="*50)
ifnotlines:
print("Заметки не найдены!")
return
fori, noteinenumerate(lines, 1):
print(f"{i}. {note.strip()}")
defshow_notes():
"""Показывает все заметки с нумерацией."""
lines=load_notes()
display_notes(lines, show_header=True)
defget_user_choice(max_choice):
"""Получает от пользователя номер выбора."""
try:
choice=int(input("Введите номер: "))
if1<=choice<=max_choice:
returnchoice
print("Неверный номер")
exceptValueError:
print("Введите число!")
returnNone
defaction_add_note():
print("="*50)
note=input("Введите заметку, которую хотите добавить: ").strip()
ifnotnote:
print("Заметка не может быть пустой!")
return
withopen(NOTES_FILE, "a", encoding="utf-8") asf:
f.write(note+"\n")
print("="*50)
print("Заметка добавлена!")
defaction_update_note():
"""Обновляет существующую заметку."""
print("="*50)
lines=load_notes()
ifnotlines:
print("Нет заметок для обновления!")
return
display_notes(lines, show_header=False)
choice=get_user_choice(len(lines))
ifnotchoice:
return
new_note=input("Введите новый текст заметки: ")
lines[choice-1] =new_note+"\n"
save_notes(lines)
print("="*50)
print("Заметка обновлена!")
defaction_delete_note():
"""Удаляет заметку из файла."""
print("="*50)
lines=load_notes()
ifnotlines:
print("Нет заметок для удаления!")
return
display_notes(lines, show_header=False)
choice=get_user_choice(len(lines))
ifnotchoice:
return
deleted_note=lines[choice-1].strip()
dellines[choice-1]
save_notes(lines)
print("="*50)
print(f"Заметка '{deleted_note}' удалена!")
defaction_search_notes():
"""Поиск заметок по ключевому слову."""
print("="*50)
keyword=input("Введите ключевое слово для поиска: ").strip().lower()
ifnotkeyword:
print("Ключевое слово не может быть пустым!")
return
lines=load_notes()
ifnotlines:
print("Нет заметок для поиска!")
return
found= []
fornoteinlines:
ifkeywordinnote.lower():
found.append(note)
iffound:
print(f"\nНайдено {len(found)} заметок:")
display_notes(found, show_header=False)
else:
print("Заметки не найдены!")
defmain():
"""Главный цикл программы."""
clear_console()
init_notes_file()
menu= {
"1": ("Добавить заметку", action_add_note),
"2": ("Обновить заметку", action_update_note),
"3": ("Удалить заметку", action_delete_note),
"4": ("Посмотреть заметки", show_notes),
"5": ("Поиск заметок", action_search_notes),
}
whileTrue:
print("="*50)
print("МЕНЕДЖЕР ЗАМЕТОК".center(50))
print("="*50)
forkey, (name, _) inmenu.items():
print(f"{key}. {name}")
print("0. Выйти")
print("="*50)
choice=input("Выберите вариант: ").strip()
ifchoice=="0":
print("До свидания!")
break
ifchoiceinmenu:
_, action=menu[choice]
action()
else:
print("Неверный выбор!")
wait_for_enter()
if__name__=='__main__':
main()