Remember
A with block manages a file resource. Writing stores text; reopening for reading retrieves it, and the context manager closes the file.
A with block manages a file resource. Writing stores text; reopening for reading retrieves it, and the context manager closes the file.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
with open("lesson.txt", "w", encoding="utf-8") as file:
file.write('tea')
with open("lesson.txt", encoding="utf-8") as file:
text = file.read()
print(text)Top-level scope
<_io.TextIOWrapper name='lesson.txt' mode='r' encoding='utf-8'>Object 3 · str'tea'A with block manages a file resource. Writing stores text; reopening for reading retrieves it, and the context manager closes the file.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
with open("lesson.txt", "w", encoding="utf-8") as file:
file.write('tea')
with open("lesson.txt", encoding="utf-8") as file:
text = file.read()
print(text)
|
v
DISPLAYED RESULT
tea
FINAL BINDINGS
file --> object 2 (TextIOWrapper)
text --> object 3 (str)
object 2: <_io.TextIOWrapper name='lesson.txt' mode='r' encoding='utf-8'>
object 3: 'tea'Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
with open("lesson.txt", "w", encoding="utf-8") as file:
file.write('tea')
with open("lesson.txt", encoding="utf-8") as file:
text = file.read()
print(text)Top-level scope
<_io.TextIOWrapper name='lesson.txt' mode='r' encoding='utf-8'>Object 3 · str'tea'The example has finished. Compare the final output with the values and references above.
tea
What do you expect this program to print?
with open("lesson.txt", "w", encoding="utf-8") as file:
file.write('tea')
with open("lesson.txt", encoding="utf-8") as file:
text = file.read()
print(text)In this lesson, you’ll learn how to work with files in Python — how to create, read, write, update, and delete files. This is often called CRUD operations: Create, Read, Update, Delete.
This will create a file and write some text inside it.
file = open("example.txt", "w")
file.write("Hello from Python!")
file.close()
open("example.txt", "w") opens a file in write mode. If the file doesn’t exist, it will be created.file.write(...) writes the text inside the file.file.close() closes the file to save changes.A new file called example.txt is created with this content:
Hello from Python!
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
"r" means read mode.file.read() reads all the content of the file.print(content) shows the file content on screen.Hello from Python!
file = open("example.txt", "a")
file.write("\nAdding a second line.")
file.close()
"a" stands for append mode — it adds text to the end without removing what’s already there.\n is used to go to a new line.Hello from Python!
Adding a second line.
Python doesn’t delete files directly — but we can use a helper from the os module:
import os
os.remove("example.txt")
import os loads the module to work with the operating system.os.remove(...) deletes the file named example.txt.The file is permanently deleted from your folder.
Reason: Leaving files open can cause problems like data not being saved.
with open(...) instead of open() and close()This is the safer and preferred way. Python closes the file for you automatically.
with open("example.txt", "r") as file:
content = file.read()
print(content)
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
else:
print("File does not exist.")
Reason: Trying to delete a file that doesn’t exist will cause an error.
Connect what you noticed in the example with the idea below.
A with block manages a file resource. Writing stores text; reopening for reading retrieves it, and the context manager closes the file.
Opening a file in w mode preserves its previous contents.
This is the misconception to avoid.Reaching the recap and completing the quizzes are separate milestones.