PYTHON CORE · LESSON 35

Write the file down.

with open and write · about 14 minutes

Learning with progressRead the summary for free. To save the work, log in to the account.
STEP 1

File stores data

open opens the file. w creates a file to write. with will close it after work.

with open("hello.txt", "w", encoding="utf-8") as file:
    file.write("Привет")
Text-to-file path
Codewrite(…)File.hello.txtInside.Привет

✦ A hello.txt file with text will appear on the computer.

STEP 2

The recording changes the contents

file.write records the text. If you open the same file in w mode again, the old content will be replaced.

with open("hello.txt", "w", encoding="utf-8") as file:
    file.write("Новый текст")

✦ The file will remain «Новый текст».

IN-CLASS PRACTICE

Type the code yourself

Reprint the file creation. The code here is checked by lines; to create a file on your computer, run it in VS Code.

with open("story.txt", "w", encoding="utf-8") as file:
    file.write("Жил кот")
Open the editor for class work
HOMEWORK

Solve it yourself

Напиши код, который через with open создаёт note.txt в режиме w с encoding="utf-8" и записывает в него «Привет!». Назови переменную файла file.

The answer is hidden. Use similar examples from the lesson notes.

Opening up your homework