Python Reference Library →

Python open() Function – Read, Write, and Create Files Easily

Let’s look at open() function – read, write, and create files easily

  1. Notice

    open() opens a file with a chosen mode and encoding. Use a with block to close it reliably.

  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:
    print(file.read())
Live state

Top-level scope

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

open() opens a file with a chosen mode and encoding. Use a with block to close it reliably.

Picture open() function – read, write, and create files easily

open() opens a file with a chosen mode and encoding. Use a with block to close it reliably.

Image brief

Alt text
A diagram for Python open() Function – Read, Write, and Create Files Easily. Instructions: with open("lesson.txt", "w", encoding="utf-8") as file: file.write('tea') with open("lesson.txt", encoding="utf-8") as file: print(file.read()). Displayed result: tea. The final example bindings are file --> object 2 (TextIOWrapper). object 2: <_io.TextIOWrapper name='lesson.txt' mode='r' encoding='utf-8'>
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python open() Function – Read, Write, and Create Files Easily". Teaching focus: open() opens a file with a chosen mode and encoding. Use a with block to close it reliably. 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: print(file.read()) | v DISPLAYED RESULT tea FINAL BINDINGS file --> object 2 (TextIOWrapper) object 2: <_io.TextIOWrapper name='lesson.txt' mode='r' encoding='utf-8'> 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 open() Function – Read, Write, and Create Files Easily. Instructions: with open("lesson.txt", "w", encoding="utf-8") as file: file.write('tea') with open("lesson.txt", encoding="utf-8") as file: print(file.read()). Displayed result: tea. The final example bindings are file --> object 2 (TextIOWrapper). object 2: <_io.TextIOWrapper name='lesson.txt' mode='r' encoding='utf-8'>

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:
    print(file.read())
Live state

Top-level scope

file→Object 2
Object 2 · TextIOWrapper<_io.TextIOWrapper name='lesson.txt' mode='r' encoding='utf-8'>
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:
    print(file.read())
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

open() opens a file with a chosen mode and encoding. Use a with block to close it reliably.

open() opens a file with a chosen mode and encoding. Use a with block to close it reliably.

More examples and reference

Python open() Function

The open() function in Python is used to open files and return a file object. This is the starting point for reading from or writing to a file.

Syntax

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Common Parameters:

  • file: Path to the file (required)
  • mode: Mode to open the file in (default is 'r')
  • encoding: For text files, like 'utf-8'

File Modes

ModeDescription
'r'Read (default) – file must exist
'w'Write – creates or overwrites file
'a'Append – adds to file, creates if needed
'x'Create – fails if file exists
'b'Binary mode (e.g., 'rb', 'wb')
't'Text mode (default)
'+'Update mode (read & write)

Example 1: Reading a File

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

Example 2: Writing to a File

file = open("output.txt", "w")
file.write("Hello, world!")
file.close()
Creates a file with "Hello, world!"

Example 3: Using with Statement (Best Practice)

with open("data.txt", "r") as f:
    print(f.read())

Why use with? It automatically closes the file after use, even if an error occurs.

Example 4: Reading Line by Line

with open("data.txt", "r") as f:
    for line in f:
        print(line.strip())

Common Errors

  • FileNotFoundError – when opening a non-existent file in read mode
  • PermissionError – when writing to a file you don’t have access to

Use Cases

  • Reading configuration files
  • Logging messages to a log file
  • Processing CSV or text data

Interview Tip

Always use the with open(...) pattern to handle files safely in coding interviews.

Summary

  • open() is used to read/write/create files
  • Different modes like 'r', 'w', 'a' change behavior
  • Use with to manage files safely

Practice Problem

Write a Python script to copy the contents of one file into another file:

with open("source.txt", "r") as source:
    with open("destination.txt", "w") as dest:
        dest.write(source.read())

What to remember

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

Remember

open() opens a file with a chosen mode and encoding. Use a with block to close it reliably.

Watch out for this idea

Opening with w mode appends to existing content.

This is the misconception to avoid.

Reference checks are optional and do not count toward course progress.

    Reference library →