How to Open a File in Python

What you’ll build or solve

You’ll open files in Python using with open(...), read or write text safely, and avoid common errors like wrong paths or permission issues.

When this approach works best

This approach works best when you need to:

  • Read a text file, like a config file, a log, or a simple data export.
  • Write output to a file, like a report or a saved result.
  • Append new lines to an existing file without overwriting it.

Avoid this approach when:

  • You need advanced path handling across folders. Use a dedicated guide focused on file paths.
  • You need parsing for formats like JSON or CSV. Open the file first, then use the right parsing tool for that format.

Prerequisites

  • Python 3 installed
  • You can run a Python script
  • You know what a file path is, such as notes.txt or data/report.txt

Step-by-step instructions

1) Open and read a file

Use with so Python closes the file automatically.

with open("notes.txt", "r", encoding="utf-8") as f:
    text = f.read()

print(text)

Mode "r" means read. If the file does not exist, you get a FileNotFoundError.


2) Read one line at a time

Use this approach for logs or large files.

with open("notes.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip("\n"))

What to look for:

Each line usually ends with \n. Stripping it avoids double-spaced output.


3) Write text to a file (overwrite)

Use mode "w" to create the file or replace what is already there.

report = "Status: OK\n"

with open("report.txt", "w", encoding="utf-8") as f:
    f.write(report)

If report.txt already exists, its old contents are replaced.


4) Append text to an existing file

Use mode "a" to add to the end of a file.

log_line = "Started job\n"

with open("app.log", "a", encoding="utf-8") as f:
    f.write(log_line)

What to look for:

Add \n yourself if you want each entry on a new line.


Examples you can copy

1) Read a file and skip blank lines

lines = []

with open("config.txt", "r", encoding="utf-8") as f:
    for line in f:
        cleaned = line.strip()
        if cleaned:
            lines.append(cleaned)

print(lines)

2) Copy one file into another

with open("input.txt", "r", encoding="utf-8") as src:
    with open("output.txt", "w", encoding="utf-8") as dst:
        for line in src:
            dst.write(line)

3) Append a timestamped line to a log

from datetime import datetime

line = f"{datetime.now().isoformat()} - started\n"

with open("app.log", "a", encoding="utf-8") as f:
    f.write(line)

Common mistakes and how to fix them

Mistake 1: Using the wrong path

You might write:

with open("data.txt", "r", encoding="utf-8") as f:
    text = f.read()

Why it breaks:

The file is not in the folder your script is running from, so you get FileNotFoundError.

Correct approach:

with open("data/data.txt", "r", encoding="utf-8") as f:
    text = f.read()

Make sure the relative path matches your project structure.


Mistake 2: Using the wrong mode

You might write:

with open("report.txt", "w", encoding="utf-8") as f:
    f.write("New line\n")

Why it breaks:

"w" overwrites the file each time you run the script.

Correct approach:

with open("report.txt", "a", encoding="utf-8") as f:
    f.write("New line\n")

Use "a" to append instead of overwrite.


Mistake 3: Seeing weird characters in the output

You might write:

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

Why it breaks:

Python may guess the wrong encoding for the file.

Correct approach:

with open("notes.txt", "r", encoding="utf-8") as f:
    print(f.read())

Explicitly setting encoding="utf-8" avoids common issues.


Troubleshooting

If you see FileNotFoundError, confirm the file exists where your script is running. If you use a relative path like data/file.txt, confirm the data folder is in your current working directory.

If you see PermissionError, close the file in other applications or choose a different output folder.

If your output file stays empty, confirm you used "w" or "a" mode and that you called write() with the content you expect.

If your text shows strange symbols, set encoding="utf-8" or match the file’s actual encoding.

If the same relative path works sometimes and breaks other times, you are likely running the script from different folders.


Quick recap

  • Use with open(path, mode, encoding="utf-8") as f: to open files safely.
  • Use f.read() for small files and for line in f: for large files.
  • Use "w" to overwrite and "a" to append.
  • Add \n yourself when writing lines.
  • Set encoding="utf-8" to avoid common text encoding issues.