Python .unlink()

net1372284738's avatar
Published Apr 1, 2022Updated Aug 11, 2023
Contribute to Docs

The Python .unlink() file method allows the user to delete a file path if it exists in the system or computer. .remove() is the alternative to delete a specific file.

Note: A FileNotFoundError is raised if the file is not found or isn’t in the current directory.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

This method is provided by the os module which must be imported beforehand.

import os

os.unlink("file_path")

Entire folders or directories can be removed using the .rmdir() method.

Example

Use .unlink() to delete the my_file.txt file:

import os
# Delete file path
os.unlink("path/to/my_file.txt")

Codebyte Example

In this example delete_me.txt is deleted using the complete file path and the .unlink() method:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours