Python Delete Files

Python allows you to delete files using the os module. Before deleting a file, it is recommended to check whether the file exists. Import the os Module Example Delete a File The remove() method deletes a file. Syntax Example Check if a File Exists Before Deleting Example Output: Delete an Empty Folder The rmdir() method […]

2 mins read Lesson 7 of 57 12% through track

Python allows you to delete files using the os module. Before deleting a file, it is recommended to check whether the file exists.

Import the os Module

Example

import os

Delete a File

The remove() method deletes a file.

Syntax

os.remove("file_name")

Example

import os

os.remove("sample.txt")

Check if a File Exists Before Deleting

Example

import os

if os.path.exists("sample.txt"):
    os.remove("sample.txt")
    print("File deleted")
else:
    print("File does not exist")

Output:

File deleted

Delete an Empty Folder

The rmdir() method deletes an empty folder.

Syntax

os.rmdir("folder_name")

Example

import os

os.rmdir("myfolder")

Check if a Folder Exists

Example

import os

if os.path.exists("myfolder"):
    os.rmdir("myfolder")
    print("Folder deleted")
else:
    print("Folder does not exist")

Output:

Folder deleted

Handle File Deletion Errors

Example

import os

try:
    os.remove("sample.txt")
    print("File deleted")
except FileNotFoundError:
    print("File not found")

Output:

File not found

Delete File Using Path

Example

import os

file_path = "files/sample.txt"

if os.path.exists(file_path):
    os.remove(file_path)
    print("File deleted")

Output:

File deleted

Summary

  • Use the os module to delete files and folders.
  • os.remove() deletes a file.
  • os.rmdir() deletes an empty folder.
  • Always check file existence before deleting.
  • Use try...except to handle deletion errors.
  • Deleting a file permanently removes it from the system.