Python Read, Write, Create and Delete Files

Create, read, write, append and delete files safely, choosing the right open() mode and encoding.

Lesson 47 of 107Intermediate12 min read

Every file goes through the same lifecycle: it is created, written, read, perhaps appended to, and eventually deleted. In Python each step is one or two lines, mostly using open() with the right mode and the pathlib module:

Python
from pathlib import Path
path = Path("nest_log.txt")
path.write_text("Swallow: 3 eggs\n", encoding="utf-8")   # create and write
print(path.read_text(encoding="utf-8"))                  # read
path.unlink()                                            # delete

This lesson goes step by step through the lifecycle, with the details that prevent data loss: which modes overwrite and which refuse to, why you should always state an encoding, how binary files differ, and how to delete safely. The file handling lesson introduced reading and writing; here you'll see the full picture. The examples belong to a bird survey keeping nest observations.

Modes

The mode passed to open() decides what you can do and what happens to an existing file:

ModeIf file existsIf missingUse
"r"read from startFileNotFoundErrorreading (default)
"w"emptied firstcreatedreplacing contents
"a"write at endcreatedlogs, adding records
"x"FileExistsErrorcreatednew files that must not overwrite
"r+"read and writeFileNotFoundErrorediting in place (rare)

Add "b" for binary ("rb", "wb") and "t" for text, which is the default.

"w" is the dangerous one: the existing contents are discarded the moment the file is opened, before you write anything. When a file must not be replaced, for example a survey record for a specific date, use "x" and handle FileExistsError. When adding to a history, use "a".

Encoding

Text files are stored as bytes, and an encoding says how characters map to bytes. If you don't specify one, Python uses a platform default, which may differ between Windows and Linux, so a file written on one machine can be misread on another:

Python
with open("species.txt", "w", encoding="utf-8") as file:
    file.write("Fauvette à tête noire\n")

Always pass encoding="utf-8" for text unless you know the file uses something else. Reading a file with the wrong encoding raises UnicodeDecodeError or, worse, silently shows garbled characters. Python 3.15 is expected to make UTF-8 the default everywhere, but stating it explicitly works on every version.

Images, audio, PDFs and other non-text files must be opened in binary mode, which reads and writes bytes without any decoding: with open("nest.jpg", "rb") as file: data = file.read(). Binary mode doesn't accept an encoding argument.

Context lifetime

Opening a file inside a with statement makes Python close it automatically when the block ends, including when an exception is raised. Closing matters: written data may sit in a buffer until the file is closed, and operating systems limit how many files a program can have open.

Python
with open("nest_log.txt", "a", encoding="utf-8") as log:
    log.write("Robin: 4 eggs\n")
    log.write("Wren: 6 eggs\n")
# closed and flushed here

Keep the file open for all the related writes, rather than reopening it for every line. print("Robin: 4 eggs", file=log) is a handy alternative to write() because it adds the newline for you. For small files, Path.write_text() and Path.read_text() open, write or read, and close in one call. The context managers lesson explains how with works underneath.

Removal

Path.unlink() deletes a file; os.remove() does the same. Deletion is permanent: Python doesn't use the recycle bin.

Python
from pathlib import Path
draft = Path("draft_notes.txt")
draft.unlink(missing_ok=True)     # no error if already gone (Python 3.8+)

Without missing_ok=True, deleting a missing file raises FileNotFoundError. Deleting a folder needs Path.rmdir() (empty folders only) or shutil.rmtree() (everything inside, with no confirmation).

Before deleting, make sure the path is the one you intend: print it, check path.is_file(), and never build deletion paths from unchecked user input. Programs that clean up their own temporary files are safer using the tempfile module, which creates files in a dedicated temporary folder and removes them automatically.

Independent practice and a worked check

Task: use a disposable observation file to demonstrate exclusive creation, reading, appending and removal.

Python
from pathlib import Path

obs = Path("practice_obs.txt")
obs.unlink(missing_ok=True)

with obs.open("x", encoding="utf-8") as f:
    f.write("Blackbird: 2 eggs\n")
with obs.open("a", encoding="utf-8") as f:
    f.write("Blue tit: 9 eggs\n")

lines = obs.read_text(encoding="utf-8").splitlines()
print(lines)                 # ['Blackbird: 2 eggs', 'Blue tit: 9 eggs']
obs.unlink()
print(obs.exists())          # False

splitlines() removes the newline characters, giving clean strings. For the worked check, the mode that refuses to overwrite an existing file is "x": it raises FileExistsError instead.

Reference and next practice

The documentation for open() lists every mode, and pathlib covers read_text, write_text and unlink. Continue with directory operations and JSON handling. Practise with the Python exercises and Python quiz.

Read, Write, Create and Delete Files Summary

  • Modes: r reads existing text, w overwrites or creates, a appends and x creates exclusively.
  • Encoding: An explicit text encoding makes reading and writing predictable.
  • Context lifetime: with closes the file when its block ends.
  • Removal: Path.unlink removes a file while directory removal uses different operations.

Read, Write, Create and Delete Files Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Read, Write, Create and Delete Files in a small program

Python
from pathlib import Path
path = Path("nest_demo.txt")
with path.open("w", encoding="utf-8") as stream:
    stream.write("Swallow: 3 eggs\n")
print(path.read_text(encoding="utf-8").strip())
path.unlink()
Output
Swallow: 3 eggs
Line-by-line explanation
  1. Line 2A Path object represents the file location; nothing is created yet.
  2. Lines 3 to 4Mode "w" creates the file and writes one line inside a with block.
  3. Line 5read_text() reads it back; strip() removes the trailing newline.
  4. Line 6unlink() deletes the file, so the demo leaves nothing behind.
Example 2

The whole lifecycle with every mode

Python
from pathlib import Path

path = Path("survey_2026.txt")
path.unlink(missing_ok=True)

with open(path, "x", encoding="utf-8") as f:
    f.write("Swallow: 3 eggs\n")

try:
    open(path, "x", encoding="utf-8")
except FileExistsError:
    print("Refused to overwrite", path.name)

with open(path, "a", encoding="utf-8") as f:
    f.write("Robin: 4 eggs\n")

with open(path, encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):
        print(number, line.rstrip())

print(path.stat().st_size, "bytes")
path.unlink()
print("Exists afterwards?", path.exists())
Output
Refused to overwrite survey_2026.txt
1 Swallow: 3 eggs
2 Robin: 4 eggs
30 bytes
Exists afterwards? False
Line-by-line explanation
  1. Line 4Removing any leftover file makes the demo repeatable.
  2. Lines 6 to 7"x" creates the file because it doesn't exist yet.
  3. Lines 9 to 12A second "x" open fails instead of destroying the first record.
  4. Lines 14 to 15"a" adds a line at the end, keeping the existing one.

Common Read, Write, Create and Delete Files Mistakes

Opening with "w" to add a line

Don't
with open("nest_log.txt", "w", encoding="utf-8") as log:
    log.write("Wren: 6 eggs\n")      # every earlier record is gone
Do
with open("nest_log.txt", "a", encoding="utf-8") as log:
    log.write("Wren: 6 eggs\n")

"w" empties the file as soon as it opens. Use "a" to add, and "x" to create a file that must not already exist.

Reading binary data in text mode

Don't
with open("nest.jpg") as f:
    data = f.read()          # UnicodeDecodeError or corrupted data
Do
with open("nest.jpg", "rb") as f:
    data = f.read()          # bytes

Read, Write, Create and Delete Files in Real Projects

File lifecycles in real applications

Applications write logs in append mode, export reports with "w" to a new file name each day, and use "x" to claim lock files or one-off output so two processes can't overwrite each other. Important files are often written atomically: the program writes to a temporary file in the same folder, then calls os.replace(temp, final), so readers see either the old complete file or the new one, never a half-written file.

Clean-up jobs delete old exports and temporary files on a schedule. Well-written ones log every path they remove, refuse to delete outside a known folder, and use missing_ok=True so a file that's already gone isn't treated as a failure.

Read, Write, Create and Delete Files FAQ

How do I create a new file in Python?

Open it in write mode, open("name.txt", "w", encoding="utf-8"), or use "x" to create it only if it doesn't already exist. Path("name.txt").touch() creates an empty file without opening it.

How do I append to a file instead of overwriting it?

Open it with mode "a". Everything you write is added at the end, and the file is created if it doesn't exist. Mode "w" replaces the whole file.

How do I delete a file in Python?

Call Path("name.txt").unlink() or os.remove("name.txt"). Pass missing_ok=True to unlink() to ignore a file that doesn't exist. Deleted files are not sent to the recycle bin.

What is the default encoding when opening a file in Python?

It depends on the operating system and locale, often UTF-8 on macOS and Linux and a legacy code page such as cp1252 on Windows. Pass encoding="utf-8" explicitly so your program behaves the same everywhere.

How do I check if a file exists before opening it?

Path("name.txt").exists() or is_file() returns True or False. For writing, mode "x" is safer than checking first, because it creates the file and fails if it exists in a single step.

Read, Write, Create and Delete Files Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Which mode refuses to overwrite an existing file?

Multiple choicemedium

Which review concern is valid for read, write, create and delete files?

Read, Write, Create and Delete Files Quiz

2 questions to check what you learned.

  1. Which mode refuses to overwrite an existing file?

    • w
    • x
    • Python ignores the distinction
  2. Which statement correctly describes context lifetime?

    • with closes the file when its block ends.
    • Only the example output matters, not the rule
    • Every operation has the same behavior