Text files · Текстовые файлы
Files keep data
- Variables vanish when a program ends; a file stores data so it lasts.
- The exam covers reading from and writing to text files.
- Work in three steps: open, read or write, then close.
Файлы хранят данные
- Переменные исчезают после завершения программы; файл сохраняет данные, чтобы они остались.
- Экзамен охватывает чтение из и запись в текстовые файлы.
- Работайте в три шага: открыть, прочитать или записать, затем закрыть.
Writing to a file
open(name, "w")opens a file for writing ("w"overwrites what was there).withcloses the file automatically when the block ends.\nstarts a new line in the file.
Запись в файл
open(name, "w")открывает файл для записи ("w"перезапишет то, что было там).withавтоматически закрывает файл при завершении блока.\nначинает новую строку в файле.
with open("notes.txt", "w") as f:
f.write("Hello\n")
f.write("World\n")
Reading a file
open(name, "r")opens a file for reading..read()pulls in the whole contents as one string.
Чтение файла
open(name, "r")открывает файл для чтения..read()загружает всё содержимое как одну строку.
with open("notes.txt", "r") as f:
text = f.read()
print(text)
Reading line by line
- Looping over the file gives one line at a time — handy for totalling or counting.
Чтение построчно
- Цикл по файлу выдает одну строку за раз — удобно для суммирования или подсчета.
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
In the exam: file handling
- Pseudocode opens a file for a mode, reads or writes, then closes it.
На экзамене: работа с файлами
- Псевдокод открывает файл в режиме, читает или записывает, затем закрывает его.
OPENFILE "notes.txt" FOR WRITE
WRITEFILE "notes.txt", "Hello"
CLOSEFILE "notes.txt"
Common mistakes
- Open, then read or write, then close the file.
- A line you read still carries its newline character.
Распространенные ошибки
- Откройте, затем прочитайте или запишите, затем закройте файл.
- Прочитанная строка все еще содержит символ переноса строки.
Now you try
- Write a file, then open it again to read it back.
- Press Check answer to test your code.
Теперь попробуйте сами
- Запишите файл, затем снова откройте его, чтобы прочитать обратно.
- Нажмите Check answer (Проверить ответ), чтобы протестировать свой код.
Using a file · Использование файла
A file is used in three steps: open, read or write, close. · Файл используется в трех шагах: открыть, прочитать или записать, закрыть.
In one run: write the line Cambridge to a file called school.txt, then open it again, read it, and print what you read. · В одном проходе: запишите строку Cambridge в файл с именем school.txt, затем откройте его снова, прочитайте и print то, что прочитали.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
The starter writes three lines to a file. 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. · Нажмите Запустить, чтобы увидеть результат здесь.
The starter writes 10, 20, 30 to a file, one per line. 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. · Нажмите Запустить, чтобы увидеть результат здесь.