Python File Operations

Let’s look at file operations

  1. Notice

    A with block manages a file resource. Writing stores text; reopening for reading retrieves it, and the context manager closes the file.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
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)
Live state

Top-level scope

file→Object 2
text→Object 3
Object 2 · TextIOWrapper<_io.TextIOWrapper name='lesson.txt' mode='r' encoding='utf-8'>Object 3 · str'tea'
This step

A with block manages a file resource. Writing stores text; reopening for reading retrieves it, and the context manager closes the file.

Picture file operations

A with block manages a file resource. Writing stores text; reopening for reading retrieves it, and the context manager closes the file.

Image brief

Alt text
A diagram for Python File Operations. 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). Displayed result: tea. The final example bindings are file --> object 2 (TextIOWrapper); text --> object 3 (str). object 2: <_io.TextIOWrapper name='lesson.txt' mode='r' encoding='utf-8'>; object 3: 'tea'
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python File Operations". Teaching focus: A with block manages a file resource. Writing stores text; reopening for reading retrieves it, and the context manager closes the file. Depict exactly the relationships and labels in this reference diagram: 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' Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python File Operations. 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). Displayed result: tea. The final example bindings are file --> object 2 (TextIOWrapper); text --> object 3 (str). object 2: <_io.TextIOWrapper name='lesson.txt' mode='r' encoding='utf-8'>; object 3: 'tea'

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
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)
Live state

Top-level scope

file→Object 2
text→Object 3
Object 2 · TextIOWrapper<_io.TextIOWrapper name='lesson.txt' mode='r' encoding='utf-8'>Object 3 · str'tea'
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
tea

What do you expect this program to print?

What does this example display?

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)
What does this example display?
Choose one answer. You can try again.

Answer and explanation

tea

Follow the printed values in order. The output is: tea

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

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.

More examples and reference

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.

1. Creating and Writing to a File

This will create a file and write some text inside it.

file = open("example.txt", "w")
file.write("Hello from Python!")
file.close()    

Explanation:

  • 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.

What Happens?

A new file called example.txt is created with this content:

Hello from Python!

2. Reading from a File

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()    

Explanation:

  • "r" means read mode.
  • file.read() reads all the content of the file.
  • print(content) shows the file content on screen.
Hello from Python!

3. Updating (Appending) a File

file = open("example.txt", "a")
file.write("\nAdding a second line.")
file.close()    

Explanation:

  • "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.

Output in the file:

Hello from Python!
Adding a second line.

4. Deleting a File

Python doesn’t delete files directly — but we can use a helper from the os module:

import os
os.remove("example.txt")    

Explanation:

  • import os loads the module to work with the operating system.
  • os.remove(...) deletes the file named example.txt.

After this:

The file is permanently deleted from your folder.

Best Practices for File Handling

1. Always close your files

Reason: Leaving files open can cause problems like data not being saved.

2. Use 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)

3. Always check if the file exists before deleting

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.

What to remember

Connect what you noticed in the example with the idea below.

Remember

A with block manages a file resource. Writing stores text; reopening for reading retrieves it, and the context manager closes the file.

Watch out for this idea

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.

    Next lesson: Python Exceptions →