Files: збереження і читання data

Повертаємось до Python.
У попередній лекції ти вивчив functions.
Твої програми навчилися organize code у reusable blocks.
Ти писав щось таке:
def greet_user(name):
print(f"Hello, {name}!")
Дуже добре.
Functions зробили твій code cleaner.
Менше repetition.
Менше copy-paste chaos.
Менше “чому я написав це саме сім разів?”
Excellent progress.
Але тепер маємо іншу проблему.
Твоя program може зберігати data у variables.
Твоя program може зберігати lists.
Твоя program може зберігати dictionaries.
Але коли program stops, everything disappears.
Дуже sad.
Дуже temporary.
Приклад:
tasks = ["Buy milk", "Study Python", "Drink coffee"]
Цей list існує, поки program running.
Але коли program ends?
Gone.
Як motivation після читання error message на 300 lines.
Files вирішують цю проблему.
Files дозволяють твоїй program save data.
Потім program може read that data later.
Це великий крок.
Programs стають набагато useful, коли можуть remember things.
Tasks.
Notes.
Contacts.
Settings.
Reports.
Logs.
Tiny memories.
Дуже useful.
Дуже Python.
Що ти вивчиш
У цій лекції ти вивчиш:
- чому files корисні;
- як записувати text у file;
- як читати text з file;
- як використовувати
open(); - чому
with open()важливий; - як працюють file modes;
- як записувати multiple lines;
- як читати line by line;
- як append data to a file;
- як save a list;
- як load a list from a file;
- як побудувати small task manager, який remembers tasks;
- типові beginner mistakes з files.
До кінця цієї лекції твої programs більше не будуть забувати все immediately.
Вони зможуть save data.
Read data.
Append data.
Load data.
Дуже powerful.
Дуже practical.
Дуже “тепер ця program стає useful”.
Чому files важливі
Variables live in memory.
Files live on disk.
Variable temporary:
name = "Anna"
Коли program ends, variable disappears.
File може залишитися після завершення program.
Наприклад:
notes.txt
tasks.txt
contacts.txt
report.txt
Твоя program може write data into a file.
Пізніше program може open the file and read the data.
Це важливо для багатьох real programs.
Examples:
Task manager saves tasks.
Notes app saves notes.
Calculator saves history.
Game saves progress.
Website writes logs.
Script writes a report.
Без files твоя program має дуже коротку memory.
Як goldfish with a keyboard.
Cute.
Not very useful.
Запис у file
Створи файл:
write_file.py
Напиши:
file = open("message.txt", "w")
file.write("Hello from Python!")
file.close()
Запусти:
python write_file.py
або:
python3 write_file.py
Python створить file called:
message.txt
Всередині file ти маєш побачити:
Hello from Python!
Цей рядок відкриває file:
file = open("message.txt", "w")
Цей рядок writes text:
file.write("Hello from Python!")
Цей рядок closes the file:
file.close()
Дуже важливо:
Always close files if you open them manually.
Але Python має кращий спосіб.
Бо Python побачив, що humans forget things, і сказав:
Fine, I will help.
Використання with open()
Кращий спосіб — використовувати with open().
Приклад:
with open("message.txt", "w") as file:
file.write("Hello from Python!")
Це робить те саме.
Але automatically closes the file.
Набагато краще.
Набагато safer.
Набагато менше “oops, I forgot close()”.
Створи файл:
write_file_with.py
Напиши:
with open("message.txt", "w") as file:
file.write("Hello from Python with with open()!")
Запусти.
Відкрий message.txt.
Ти маєш побачити:
Hello from Python with with open()!
Відтепер використовуй:
with open(...)
Це recommended style.
Cleaner.
Safer.
More professional.
Less likely to make Python sigh.
File modes
Коли ти відкриваєш file, ти вибираєш mode.
Mode каже Python, що ти хочеш зробити.
Common modes:
"r" read
"w" write
"a" append
Приклад:
open("file.txt", "r")
означає:
Open file for reading.
Приклад:
open("file.txt", "w")
означає:
Open file for writing.
Приклад:
open("file.txt", "a")
означає:
Open file for appending.
Важливе warning:
"w" overwrites the file.
Якщо file вже має content, "w" replaces it.
No mercy.
No drama.
Just gone.
Python з "w" mode такий:
New file. New life. Old content? Goodbye.
Будь обережний.
Запис multiple lines
Можна записувати multiple lines через \n.
Приклад:
with open("notes.txt", "w") as file:
file.write("First line\n")
file.write("Second line\n")
file.write("Third line\n")
\n означає:
new line
Після запуску program, notes.txt міститиме:
First line
Second line
Third line
Без \n все буде в одному line.
Приклад:
file.write("First")
file.write("Second")
Result:
FirstSecond
Не beautiful.
Не readable.
Дуже stuck together.
Використовуй \n, коли хочеш new line.
Tiny symbol.
Big formatting power.
Читання file
Створи file called:
message.txt
Поклади всередину цей text:
Hello from a file!
Тепер створи Python file:
read_file.py
Напиши:
with open("message.txt", "r") as file:
content = file.read()
print(content)
Запусти.
Output:
Hello from a file!
Цей рядок відкриває file for reading:
with open("message.txt", "r") as file:
Цей рядок reads the whole file:
content = file.read()
Потім ми print it:
print(content)
Дуже simple.
Дуже useful.
Твоя program щойно read data from disk.
Small moment.
Big power.
Reading whole file vs lines
read() reads the whole file.
Приклад:
with open("notes.txt", "r") as file:
content = file.read()
Це нормально для small files.
Але іноді треба read line by line.
Приклад:
with open("notes.txt", "r") as file:
for line in file:
print(line)
Якщо notes.txt містить:
First line
Second line
Third line
Output може виглядати так:
First line
Second line
Third line
Чому extra blank lines?
Бо кожен line already has a newline at the end.
А print() додає ще один newline.
Very generous.
Too generous.
Ми можемо fix it через .strip().
Використання strip()
.strip() removes extra whitespace from the beginning and end of a string.
Також removes newline characters.
Приклад:
text = "Hello\n"
clean_text = text.strip()
print(clean_text)
Output:
Hello
Використовуй це при reading lines:
with open("notes.txt", "r") as file:
for line in file:
print(line.strip())
Тепер output cleaner:
First line
Second line
Third line
.strip() дуже useful, коли читаєш files.
Files часто містять newlines.
Humans часто не хочуть бачити weird spacing.
Python дає тобі .strip().
Small tool.
Big relief.
Appending to a file
Write mode "w" overwrites a file.
Append mode "a" adds to the end.
Створи файл:
append_file.py
Напиши:
with open("notes.txt", "a") as file:
file.write("New note\n")
Запусти його multiple times.
Кожного разу Python додає:
New note
у кінець file.
Це useful для:
logs
notes
tasks
history
reports
Append mode safer, коли ти не хочеш delete old content.
Пам’ятай:
"w" writes from zero.
"a" adds to the end.
Дуже important.
Дуже file survival.
Запис user input у file
Створи файл:
save_note.py
Напиши:
note = input("Write a note: ")
with open("notes.txt", "a") as file:
file.write(note + "\n")
print("Note saved.")
Приклад:
Write a note: Study Python files
Program saves the note into:
notes.txt
Якщо запустиш її again, вона додасть another note.
Це вже useful.
Tiny note saver.
Not fancy.
Not cloud-based.
Not subscription.
Just a file.
Beautiful.
Reading saved notes
Створи файл:
show_notes.py
Напиши:
with open("notes.txt", "r") as file:
for line in file:
print(f"- {line.strip()}")
Якщо notes.txt містить:
Study Python files
Drink coffee
Build something useful
Output:
- Study Python files
- Drink coffee
- Build something useful
Тепер у тебе є дві programs:
save_note.py
show_notes.py
Одна saves notes.
Одна reads notes.
Tiny system.
Very humble.
Very useful.
The beginning of software.
With fewer login forms.
For now.
FileNotFoundError
Якщо ти пробуєш read file, якого не існує, Python дає error.
Приклад:
with open("missing.txt", "r") as file:
content = file.read()
Error:
FileNotFoundError
Чому?
Бо "missing.txt" не існує.
Python не може read a file that is not there.
Very logical.
Very annoying.
Один simple way — create the file first.
Інший way — handle the error.
Ми вивчимо error handling глибше later.
Поки що remember:
Reading requires the file to exist.
Writing can create a file.
Appending can create a file if it does not exist.
Це important.
Дуже practical.
Дуже “why did my script crash?” practical.
Saving a list to a file
Уяви, що ми маємо list:
tasks = ["Buy milk", "Study Python", "Clean desk"]
Можна save each item on a separate line.
Приклад:
tasks = ["Buy milk", "Study Python", "Clean desk"]
with open("tasks.txt", "w") as file:
for task in tasks:
file.write(task + "\n")
File tasks.txt міститиме:
Buy milk
Study Python
Clean desk
Це simple і useful.
Кожен task стає one line.
List у Python стає lines in a file.
Дуже clear.
Дуже beginner-friendly.
Дуже practical.
Loading a list from a file
Тепер можна read the file і rebuild the list.
Приклад:
tasks = []
with open("tasks.txt", "r") as file:
for line in file:
tasks.append(line.strip())
print(tasks)
Output:
['Buy milk', 'Study Python', 'Clean desk']
Що відбувається?
Start with an empty list.
Open the file.
Read each line.
Remove newline with strip().
Append the clean text to the list.
Тепер file знову став Python list.
Це дуже important.
Так твоя program може remember data between runs.
Save list.
Close program.
Open program later.
Load list.
Memory achieved.
Tiny victory.
Building helper functions
Ми вже знаємо functions.
Тому можемо organize file logic into functions.
Приклад:
def save_tasks(tasks):
with open("tasks.txt", "w") as file:
for task in tasks:
file.write(task + "\n")
І:
def load_tasks():
tasks = []
with open("tasks.txt", "r") as file:
for line in file:
tasks.append(line.strip())
return tasks
Тепер main program може використовувати:
tasks = load_tasks()
save_tasks(tasks)
Це cleaner.
Functions і files добре працюють together.
Functions organize the behavior.
Files store the data.
Very nice.
Very real software energy.
Simple handling missing file
Якщо file не існує, load_tasks() впаде.
Ми можемо handle it через try і except.
Не панікуй.
Це just a simple version.
Приклад:
def load_tasks():
tasks = []
try:
with open("tasks.txt", "r") as file:
for line in file:
tasks.append(line.strip())
except FileNotFoundError:
pass
return tasks
Що відбувається?
Try to open tasks.txt.
If it exists, load tasks.
If it does not exist, ignore the error.
Return an empty list.
Це useful.
Перший раз, коли ти запускаєш program, file може ще не існувати.
Це normal.
Program не має explode dramatically.
Цей try і except keeps it calm.
Like Python yoga.
Mostly.
Міні-програма: save one task
Створи файл:
save_task.py
Напиши:
task = input("Task: ")
with open("tasks.txt", "a") as file:
file.write(task + "\n")
print("Task saved.")
Запусти.
Приклад:
Task: Study Python files
Запусти again.
Приклад:
Task: Build a small app
Тепер tasks.txt містить:
Study Python files
Build a small app
Це вже useful little script.
Small.
Simple.
But it remembers.
And remembering is powerful.
Unless it remembers embarrassing variable names.
Then less powerful.
Міні-програма: show tasks
Створи файл:
show_tasks.py
Напиши:
try:
with open("tasks.txt", "r") as file:
print("Tasks:")
for line in file:
print(f"- {line.strip()}")
except FileNotFoundError:
print("No tasks found.")
Якщо file exists, it shows tasks.
Якщо file does not exist, it prints:
No tasks found.
Це better than crashing.
Crashing is educational.
But not always friendly.
Good program handles simple problems.
Missing file is a simple problem.
Mostly.
Міні-програма: Task manager with files
Тепер побудуємо task manager, який remembers tasks.
Створи файл:
task_manager_files.py
Напиши:
FILE_NAME = "tasks.txt"
def load_tasks():
tasks = []
try:
with open(FILE_NAME, "r") as file:
for line in file:
tasks.append(line.strip())
except FileNotFoundError:
pass
return tasks
def save_tasks(tasks):
with open(FILE_NAME, "w") as file:
for task in tasks:
file.write(task + "\n")
def show_menu():
print("----- Task Manager -----")
print("1. Add task")
print("2. Show tasks")
print("q. Quit")
def add_task(tasks):
task = input("Task: ")
tasks.append(task)
save_tasks(tasks)
print("Task saved.")
def show_tasks(tasks):
if len(tasks) == 0:
print("No tasks yet.")
else:
print("Tasks:")
for task in tasks:
print(f"- {task}")
tasks = load_tasks()
while True:
show_menu()
choice = input("Choose an option: ").lower()
if choice == "1":
add_task(tasks)
elif choice == "2":
show_tasks(tasks)
elif choice == "q":
print("Goodbye.")
break
else:
print("Unknown option.")
Це real improvement.
До цього твій task manager forgot everything.
Тепер він saves tasks to a file.
Коли program starts, він loads tasks from the file.
Коли ти add a task, він saves the list again.
Це real program behavior.
Дуже добре.
Дуже practical.
Дуже “my code has memory now”.
Як task manager works
File name stored here:
FILE_NAME = "tasks.txt"
Ця function loads tasks:
def load_tasks():
Ця function saves tasks:
def save_tasks(tasks):
Ця function adds a task:
def add_task(tasks):
Inside add_task, we do this:
tasks.append(task)
save_tasks(tasks)
Це означає:
Add task to the list.
Save the updated list to the file.
Important idea:
The list is used while the program runs.
The file stores the data between program runs.
Це дуже важливий programming pattern.
Memory in RAM.
Storage on disk.
Твоя program now uses both.
Very serious.
Very useful.
Writing vs appending у task manager
У save_tasks ми використовуємо "w":
with open(FILE_NAME, "w") as file:
Чому не "a"?
Бо ми хочемо save the current full list.
Якщо використати "a", tasks можуть duplicate every time we save.
Приклад:
Buy milk
Study Python
Buy milk
Study Python
Not good.
Тому для saving the full list використовуй "w".
Для adding one new line directly використовуй "a".
Simple rule:
Use "w" when saving the whole current state.
Use "a" when adding one new item to the end.
Це дуже important.
Tiny mode letter.
Big difference.
Типова помилка: забути close the file
Manual way:
file = open("notes.txt", "w")
file.write("Hello")
Тут забули:
file.close()
Краще:
with open("notes.txt", "w") as file:
file.write("Hello")
Використовуй with open().
It closes the file automatically.
Це style, який треба use most of the time.
Clean.
Safe.
Professional.
No forgotten open files wandering around like lost goats.
Типова помилка: using w and deleting old data
Це може бути dangerous:
with open("notes.txt", "w") as file:
file.write("New note\n")
Якщо notes.txt already had content, it is replaced.
Gone.
Якщо хочеш add to the file, use "a":
with open("notes.txt", "a") as file:
file.write("New note\n")
Пам’ятай:
"w" overwrites.
"a" appends.
Це одна з найважливіших file lessons.
Не вчи її painful way.
Painful way very effective.
But very painful.
Типова помилка: забути newline
Неправильно:
with open("tasks.txt", "a") as file:
file.write("Buy milk")
file.write("Study Python")
File result:
Buy milkStudy Python
Правильно:
with open("tasks.txt", "a") as file:
file.write("Buy milk\n")
file.write("Study Python\n")
File result:
Buy milk
Study Python
Використовуй \n, коли кожен item має бути on a new line.
Newlines small.
But без них text becomes pasta.
Not nice pasta.
Bug pasta.
Типова помилка: reading missing file
Неправильно:
with open("tasks.txt", "r") as file:
content = file.read()
Це fails, якщо tasks.txt does not exist.
Безпечніше:
try:
with open("tasks.txt", "r") as file:
content = file.read()
except FileNotFoundError:
content = ""
Тепер program does not crash.
Вона використовує empty content, якщо file missing.
Це useful, коли file will be created later.
Багато beginner file programs fail on the first run.
Why?
Because the file does not exist yet.
Classic.
Very classic.
Типова помилка: not using strip()
Коли читаєш lines, ти можеш отримати newline characters.
Приклад:
tasks = []
with open("tasks.txt", "r") as file:
for line in file:
tasks.append(line)
Це може store:
["Buy milk\n", "Study Python\n"]
Краще:
tasks.append(line.strip())
Тепер маєш:
["Buy milk", "Study Python"]
Використовуй .strip(), коли хочеш clean text.
Especially when reading line by line.
Your future output will look better.
And less haunted.
Типова помилка: file path confusion
Це:
with open("tasks.txt", "r") as file:
шукає tasks.txt у current working directory.
Це означає:
the folder where you run the Python command
Якщо Python каже, що file missing, maybe file exists in another folder.
Приклад:
python scripts/task_manager.py
Current directory може бути не same as script folder.
Це може confuse beginners.
Very normal.
Поки що тримай Python file і text file in the same folder.
Run the command from that folder.
Simple.
Less path drama.
Path drama is real.
And sometimes spicy.
Практика
Створи файл:
practice_files.py
Напиши program, яка:
- asks the user for a name;
- asks the user for a city;
- saves both values to
profile.txt; - reads
profile.txt; - prints the saved profile.
Приклад рішення:
name = input("Name: ")
city = input("City: ")
with open("profile.txt", "w") as file:
file.write(name + "\n")
file.write(city + "\n")
with open("profile.txt", "r") as file:
lines = []
for line in file:
lines.append(line.strip())
print("----- Profile -----")
print(f"Name: {lines[0]}")
print(f"City: {lines[1]}")
Приклад:
Name: Anna
City: Rome
Output:
----- Profile -----
Name: Anna
City: Rome
Ця program writes data.
Then reads data.
Then uses the loaded data.
Дуже important pattern.
Save.
Load.
Use.
That is file handling in a nutshell.
A small nutshell.
With Python inside.
Міні-завдання
Створи файл:
notes_app.py
Твоя program має:
- use a file called
notes.txt; - show a menu;
- let the user add a note;
- let the user show all notes;
- let the user quit;
- keep notes saved between program runs.
Menu:
1. Add note
2. Show notes
q. Quit
Приклад рішення:
FILE_NAME = "notes.txt"
def show_menu():
print("----- Notes App -----")
print("1. Add note")
print("2. Show notes")
print("q. Quit")
def add_note():
note = input("Note: ")
with open(FILE_NAME, "a") as file:
file.write(note + "\n")
print("Note saved.")
def show_notes():
try:
with open(FILE_NAME, "r") as file:
print("Notes:")
has_notes = False
for line in file:
print(f"- {line.strip()}")
has_notes = True
if not has_notes:
print("No notes yet.")
except FileNotFoundError:
print("No notes yet.")
while True:
show_menu()
choice = input("Choose an option: ").lower()
if choice == "1":
add_note()
elif choice == "2":
show_notes()
elif choice == "q":
print("Goodbye.")
break
else:
print("Unknown option.")
Це real mini application.
Вона uses:
- files;
- functions;
- loops;
- conditions;
- user input;
- append mode;
- reading line by line;
- error handling for missing files.
Дуже strong.
Дуже useful.
Very beginner project, but already real.
Small notes app that remembers notes.
Not bad at all.
Extra challenge: save contacts
Створи файл:
contacts_file.py
Побудуй program, яка:
- lets the user add contacts;
- saves contacts to
contacts.txt; - shows all contacts;
- each contact has name, email, and phone.
Simple file format:
Anna,anna@example.com,123456
Marco,marco@example.com,987654
Приклад ідеї:
FILE_NAME = "contacts.txt"
def add_contact():
name = input("Name: ")
email = input("Email: ")
phone = input("Phone: ")
with open(FILE_NAME, "a") as file:
file.write(f"{name},{email},{phone}\n")
print("Contact saved.")
def show_contacts():
try:
with open(FILE_NAME, "r") as file:
print("Contacts:")
for line in file:
parts = line.strip().split(",")
if len(parts) == 3:
name = parts[0]
email = parts[1]
phone = parts[2]
print("-----")
print(f"Name: {name}")
print(f"Email: {email}")
print(f"Phone: {phone}")
except FileNotFoundError:
print("No contacts yet.")
while True:
print("----- Contact Book -----")
print("1. Add contact")
print("2. Show contacts")
print("q. Quit")
choice = input("Choose an option: ").lower()
if choice == "1":
add_contact()
elif choice == "2":
show_contacts()
elif choice == "q":
print("Goodbye.")
break
else:
print("Unknown option.")
Ця program saves structured data in a simple text format.
Важливо:
line.strip().split(",")
Це бере line like:
Anna,anna@example.com,123456
і turns it into:
["Anna", "anna@example.com", "123456"]
Це very useful idea.
Later, ти можеш learn better formats like JSON.
Але поки що simple text files enough.
One step at a time.
No need to summon the JSON dragon yet.
Checklist для початківців
Коли file code не працює, перевір:
Я використав with open()?
Я вибрав correct mode?
Я accidentally used "w" instead of "a"?
Я додав "\n" for new lines?
File exists before reading?
Should I handle FileNotFoundError?
Я використав strip() when reading lines?
Я запускаю Python from the correct folder?
Я написав file name correctly?
Я saved the file after writing the code?
File bugs often simple.
But annoying.
Especially path problems.
Якщо Python каже:
FileNotFoundError
не панікуй.
Перевір:
file name
folder
mode
current directory
Most of the time, file просто не там, де Python is looking.
Python strict.
It does not search your whole computer emotionally.
It looks where you told it to look.
Very literal.
Very Python.
Підсумок
Сьогодні ти вивчив:
- variables are temporary;
- files can store data after the program ends;
open()opens files;with open()automatically closes files;"r"means read;"w"means write and overwrite;"a"means append;write()writes text to a file;read()reads the whole file;- loops can read files line by line;
\ncreates a new line;.strip()removes extra whitespace and newlines;FileNotFoundErrorhappens when reading a missing file;- lists can be saved line by line;
- lists can be loaded from files;
- functions can organize file logic;
- task manager can remember tasks using a file.
Це величезний крок.
Твої programs тепер можуть remember things.
Вони можуть save data.
Вони можуть load data.
Вони можуть become more useful.
Саме тут small scripts починають feel like real applications.
Program with memory набагато powerful, ніж program that forgets everything.
Навіть якщо memory — це лише tiny tasks.txt.
Small file.
Big upgrade.
Наступна лекція
У наступній лекції ми вивчимо basic error handling.
Твої programs навчаться survive problems more gracefully.
Наприклад:
user enters text instead of a number
file does not exist
division by zero
wrong menu option
missing data
Замість того, щоб crashing dramatically, program зможе respond calmly.
Дуже useful.
Дуже adult.
Дуже Python.
Бо real users do strange things.
І sometimes the real user is you.
Especially at night.