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.