Python File Open: Read and Write Files

To read or change a file in Python, open it with a path and a mode. The open() function returns a file object your code can use to read or write data.

This article shows how to read a text file line by line and choose a mode when writing.

TL;DR

Use open() with a path and a mode, then use with so Python closes the file when the block ends.

  • Use ‘r’ to read and specify encoding=’utf-8′ for text.
  • A relative path starts from the process’s current working directory.
  • Use ‘w’ only when replacing existing contents is intended. Choose ‘a’ to append.

What Is open() in Python?

open() is a built-in function that takes a file path and returns a file object, the stream your code uses to read or write data. The default mode is ‘r’, which opens a text file for reading.

Pass a string or a pathlib.Path object. Relative paths use the process working directory, which may differ from the folder containing the script.

In text mode, Python decodes file bytes into str, while binary mode returns bytes. The official open() reference documents buffering and custom opener options for cases beyond a basic file read.

How to Open and Read a File in Python

For a small text file, choose a path that resolves to the file, open it in read mode with the intended encoding, and process the returned file object inside a with block.

Step 1: Put the file where the path points

Save a file named sample.txt in the directory from which you run the script. A relative path such as ‘sample.txt’ is short, but it depends on the current working directory. An absolute path names the location from the filesystem root and does not depend on where the command was started.

Step 2: Open it in read mode and process each line

I ran the saved program with python3 read_file_demo.py. It creates a UTF-8 text file, prints each line, then reports whether the file closed.

from pathlib import Path

source = Path("sample.txt")
source.write_text("First line\nSecond line\n", encoding="utf-8")

with open(source, "r", encoding="utf-8") as file:
    for line in file:
        print(line, end="")

print(f"Closed after with: {file.closed}")

The saved program prints these lines after python3 read_file_demo.py:

First line
Second line
Closed after with: True
Terminal output showing Python reading two lines and closing the file
The script prints both lines and confirms the file is closed.

The two text lines appear without extra blank lines because the loop prints each line as read. The final True confirms that leaving with closes the file, including when an exception interrupts the block.

Step 3: Read all content only when it fits

Calling file.read() returns the remaining content as one string, which is convenient for a small configuration file or short note. For a large file, iterating line by line avoids holding the entire contents in memory at once.

When you need only a fixed number of characters or bytes, pass a size to read(size). Text mode counts decoded characters, while binary mode counts bytes. A file object’s position advances as it reads, so a later read() may return an empty string if the earlier call consumed everything.

Step 4: Choose a safe write mode when changing files

Choose ‘w’ to replace a file or ‘a’ to append text. For exclusive creation, ‘x’ raises FileExistsError when the path is already present, which protects an existing file from accidental replacement.

Use ‘b’ with a mode such as ‘rb’ for images or other byte-oriented data, and leave encoding out of binary-mode calls.

For related examples, see AskPython’s guides to reading a file and writing a file.

Format values for file output

After reading text, Python gives your program strings. You can combine those values with labels or numeric formatting before printing them, without changing the contents stored in the file. Formatted string literals, usually called f-strings, are a direct option when the expression belongs inside a string.

name = "report.txt"
line_count = 12
print(f"{name}: {line_count} lines")

Python evaluates expressions inside braces and inserts the resulting values. A format specifier after a colon can control presentation, such as the number of decimal places in a measurement. This is useful when a file contains numeric text that your program has converted to a number for display.

temperature = 21.678
print(f"Temperature: {temperature:.1f} C")

For older code or a template assembled separately, str.format() fills replacement fields from supplied values.

path = "sample.txt"
size = 256
message = "File {0} contains {1} bytes".format(path, size)

Choose one formatting style for a given line so readers can see where each value enters the output.

These formatting choices affect the text your program displays or writes, not how open() locates the file or manages its lifetime. When creating a report, build the formatted string and pass it to file.write() inside a with block opened in the intended write or append mode. Decide that mode first, because formatting does not protect existing contents from truncation.

File Paths, Modes, and Errors

Check the path and mode first when opening fails. The table pairs frequent symptoms with a practical next check.

SituationWhat happensWhat to do
Relative path cannot be foundFileNotFoundErrorCheck the current working directory or pass the correct path.
Read mode on a missing fileopen() raises an OSError subtypeCreate the file first or correct its name and location.
Write mode on an existing fileExisting contents are erasedUse ‘a’ to append, or choose another output path.
Text uses an unexpected encodingCharacters may decode incorrectly or raise an errorSpecify the encoding used by the file.
Image opened as textBytes are decoded as charactersOpen it in binary mode such as ‘rb’.

When a relative path fails, print or inspect the current working directory with pathlib.Path.cwd() and compare it with the file’s location. If the data file must live beside the script regardless of launch directory, build its path from Path(__file__).parent. Interactive consoles may not define __file__, so that approach belongs in a saved script.

Python’s default text encoding can differ across environments, so pass encoding=’utf-8′ when that matches the file. Check the source format if text decoding fails.

For multiple files, put each open() call in the same with statement or nest the blocks. The file handling guide covers the broader set of file operations.

Conclusion

Opening a file starts with the correct path and mode. State the encoding for text, and treat ‘w’ as a destructive choice. For details beyond the common arguments, consult the official open() documentation and the Python tutorial on reading and writing files.

FAQ

These answers cover common questions about locating and opening a file.

How do I open a text file in Python?

Use with open(path, ‘r’, encoding=’utf-8′) as file and read or iterate over file inside the block.

Why does Python say the file was not found?

A relative path is resolved from the process’s current working directory. Check that directory and the exact filename, or provide the correct path.

Does open() close a file automatically?

open() alone does not close the file when you finish using it. A with open(…) as file block closes it when the block exits.

What is the difference between r, w, and a?

‘r’ reads an existing file, ‘w’ writes after truncating existing content, and ‘a’ writes at the end.