Text files · Текстовые файлы
Why files?
- Variables vanish when a program ends. A file keeps data on disk.
- Files let you save results and read them back later.
- They also hold more data than you would type by hand.
Зачем нужны файлы?
- Переменные исчезают при завершении программы. Файл сохраняет данные на диске.
- Файлы позволяют сохранять результаты и читать их позже.
- Они также хранят больше данных, чем можно было бы ввести вручную.
Open, use, close
open(name, mode)opens a file. The mode says what you will do."r"reads,"w"writes a fresh file (replacing any old text),"a"adds to the end.- Every file you open must be closed when you finish.
Открытие, использование, закрытие
open(name, mode)открывает файл. Режим указывает, что вы будете делать."r"читает,"w"записывает новый файл (заменяя любой старый текст),"a"добавляет в конец.- Каждый открытый вами файл должен быть закрыт по завершении работы.
The with block
with open(...) as f:opens the file and closes it for you.- All the work goes in the indented block.
- This is the safest way — the file is never left open.
Блок with
with open(...) as f:открывает файл и закрывает его за вас.- Вся работа выполняется в отступленном блоке.
- Это самый безопасный способ — файл никогда не остается открытым.
with open("greeting.txt", "w") as f:
f.write("Hi there\n")
with open("greeting.txt", "r") as f:
print(f.read())
Reading the lines
f.read()returns the whole file as one string.for line in f:reads it one line at a time.- Each line keeps its newline, so use
line.strip()to remove it.
Чтение строк
f.read()возвращает весь файл как одну строку.for line in f:читает его по одной строке за раз.- Каждая строка сохраняет символ переноса, поэтому используйте
line.strip(), чтобы удалить его.
with open("fruit.txt", "w") as f:
f.write("apple\npear\n")
with open("fruit.txt", "r") as f:
for line in f:
print(line.strip())
In Cambridge pseudocode
- The exam uses
OPENFILE,WRITEFILE,READFILE, andCLOSEFILE.
В псевдокоде Cambridge
- На экзамене используются
OPENFILE,WRITEFILE,READFILEиCLOSEFILE.
OPENFILE "notes.txt" FOR WRITE
WRITEFILE "notes.txt", "Hello"
CLOSEFILE "notes.txt"
OPENFILE "notes.txt" FOR READ
READFILE "notes.txt", line
CLOSEFILE "notes.txt"
OUTPUT line
Common mistakes
- Use
with open(...) as f:so the file closes itself. "w"erases the file first;"a"adds to the end.
Распространенные ошибки
- Используйте
with open(...) as f:, чтобы файл закрывался автоматически. "w"сначала стирает файл;"a"добавляет в конец.
Now you try
- This playground keeps files between runs, so write the file first, then read it in the same task.
- Press Check answer to test your code.
Теперь попробуйте сами
- Эта игровая площадка сохраняет файлы между запусками, поэтому сначала запишите файл, а затем прочитайте его в том же задании.
- Нажмите Check answer (Проверить ответ), чтобы протестировать свой код.
Reading a file · Чтение файла
A file is used in three steps: open, read, close. · Файл используется в три этапа: открыть, прочитать, закрыть.
In one run: write the two lines Hello and World to a file called notes.txt, then open it again, read it, and print what you read. · В одном запуске: запишите две строки Hello и World в файл под именем notes.txt, затем снова откройте его, прочитайте и print то, что вы прочитали.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Write three lines to a file, then read it back and count the lines with a loop. Store the count in count (the answer is 3). · Запишите три строки в файл, затем прочитайте их обратно и подсчитайте количество строк с помощью цикла. Сохраните счётчик в count (ответ — 3).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Write the numbers 10, 20, 30 to a file, one per line. Then read them back, convert each line with int(...), and add them up in total (the answer is 60). · Запишите числа 10, 20, 30 в файл, по одному на строку. Затем прочитайте их обратно, преобразуйте каждую строку с помощью int(...) и сложите результаты в total (ответ — 60).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.