Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk2 min

How to Delete a File if It Exists in Python

Delete a file only when present with Path.unlink(missing_ok=True) in Python 3.8 and later, or catch FileNotFoundError for older versions.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Python 3.8 and later, call Path.unlink(missing_ok=True) to remove a file if it exists and ignore it if it is already absent:

from pathlib import Path

Path("file.txt").unlink(missing_ok=True)

For Python versions before 3.8, catch FileNotFoundError around the deletion instead.

Use missing_ok=True in Python 3.8 and later

Path.unlink() removes the file or symbolic link at the given path. Its default is missing_ok=False, so an absent path raises FileNotFoundError. Set missing_ok=True to treat an already-missing path as an ordinary outcome. The parameter was added in Python 3.8; see the Python 3.11.17 pathlib documentation.

from pathlib import Path

Path("file.txt").unlink(missing_ok=True)

Use FileNotFoundError handling on older Python

For compatibility with Python versions before 3.8, catch only the exception that means the target is missing:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from pathlib import Path

try:
    Path("file.txt").unlink()
except FileNotFoundError:
    pass

The same pattern works with os.remove(path) or os.unlink(path). Catching FileNotFoundError rather than every OSError leaves permission failures and other filesystem errors visible. Choose the API that fits the rest of your code.

Choose the approach that fits your code

Approach Python support When the file is absent Best fit
Path.unlink(missing_ok=True) Python 3.8 and later Silently ignored Concise deletion when absence needs no special handling
try/except FileNotFoundError Works as a compatibility pattern, including before Python 3.8 The handler can do nothing or run custom logic Older Python or when absence requires a specific response
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Do not use file deletion to remove a directory

Path.unlink() removes a file or symbolic link, not a directory tree. To remove an empty directory, use Path.rmdir(); it raises an error if the directory is not empty. The pathlib documentation describes these path operations.

Handle paths and filesystem errors carefully

  • A relative path such as file.txt is resolved from the process’s current working directory. Use the intended path if the file is elsewhere.
  • A separate exists() check cannot guarantee that deletion will succeed: the filesystem may change between the check and the removal. Attempt deletion directly and handle FileNotFoundError if absence is expected.
  • missing_ok=True only suppresses the missing-file case. It does not make deletion succeed when permissions or another operating-system error prevents it.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.