Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Examples
  3. Write and Read a Text File

File Handling · Python example

Write and Read a Text File

Create a file in Python's virtual filesystem, then read it back.

Open the compilerAll examples
intermediatefileswithencoding

Python can read and write files. In the browser, these files live in Pyodide's in-memory filesystem and disappear when the runtime restarts.

example.py
filename = "ilovecompiler_notes.txt"

with open(filename, "w", encoding="utf-8") as file:
    file.write("ILoveCompiler file demo\n")
    file.write("Second line\n")

with open(filename, encoding="utf-8") as file:
    contents = file.read()

print(contents, end="")

How the code works

  • The first block writes two lines.
  • The second block opens the same file for reading.
  • read() returns the entire file, and end='' avoids an extra newline.

Key ideas

  • The with statement closes the file automatically.
  • Mode 'w' creates or truncates a file; the default mode is read-only.
  • encoding='utf-8' makes text handling explicit.

Try changing it

  • Read the file line by line with a for loop.
  • Append a line with mode 'a'.
  • Use pathlib.Path for a more modern interface.

Related examples

intermediate

Word Frequency Counter

Count repeated words with a dictionary and print the results in alphabetical order.

intermediate

Bank Account Class

Model a bank account with a class, methods, and simple validation.

Previous exampleCelsius to FahrenheitNext exampleBank Account Class

Expected output

ILoveCompiler file demo
Second line

Output is compared after trimming trailing whitespace on each line. Run the code to see it produced by CPython in your browser.

Practice next

Apply the same idea with automatic tests or browse a guided project.

ExercisesProjects