Pylerno
English

Text files

Read and write text while choosing a safe file mode.

On this page

The concept

Text files encode strings as bytes on disk. Specify encoding="utf-8" explicitly so the intended interpretation is clear. The mode r reads, w replaces existing content, and a appends. A with block closes the file when control leaves the block, including ordinary exception paths.

Reading one line at a time avoids loading a large file completely into memory. Lines commonly include their trailing newline. rstrip("\n") removes only that line-ending character rather than every meaningful surrounding space. The example uses a temporary directory to make overwrite practice safe.

Worked example

python
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory(prefix="python_text_") as temporary:
    path = Path(temporary) / "notes.txt"
    with path.open("w", encoding="utf-8") as file:
        file.write("First lesson\n")
        file.write("Python is fun\n")
    with path.open("a", encoding="utf-8") as file:
        file.write("Keep practicing\n")
    with path.open("r", encoding="utf-8") as file:
        for line_number, line in enumerate(file, start=1):
            print(line_number, line.rstrip("\n"))

Trace the result

  1. The w block creates two lines of initial content.
  2. The a block adds another line without removing the first two.
  3. The read loop numbers each line from 1 and removes its final newline before printing.
text
1 First lesson
2 Python is fun
3 Keep practicing
Line-by-line walkthrough

Line 1: from pathlib import Path

Import Path from pathlib. This supplies filesystem path values. The caller can now use the imported names directly.

Line 2: from tempfile import TemporaryDirectory

Import TemporaryDirectory from tempfile. This supplies temporary files and directories. The caller can now use the imported names directly.

Lines 4–13: with TemporaryDirectory(prefix="python_text_") as temporary:

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Line 5: path = Path(temporary) / "notes.txt"

Evaluate Path(temporary) / 'notes.txt', then bind or update path with the result. Assignment itself does not imply a deep copy.

Lines 6–8: with path.open("w", encoding="utf-8") as file:

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Line 7: file.write("First lesson\n")

Call file.write to write text to the open stream. This call may have an effect even when its return value is not assigned.

Line 8: file.write("Python is fun\n")

Call file.write to write text to the open stream. This call may have an effect even when its return value is not assigned.

Lines 9–10: with path.open("a", encoding="utf-8") as file:

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Line 10: file.write("Keep practicing\n")

Call file.write to write text to the open stream. This call may have an effect even when its return value is not assigned.

Lines 11–13: with path.open("r", encoding="utf-8") as file:

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Lines 12–13: for line_number, line in enumerate(file, start=1):

Obtain each item from enumerate(file, start=1) and bind it to (line_number, line) before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.

Line 13: print(line_number, line.rstrip("\n"))

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Common mistake

Opening an important file with w truncates it. Practice on disposable files and decide overwrite policy before opening a destination.

Check your understanding

Which open mode adds text at the end of an existing file?

Choose one answer

Search documentation

Share this page