How to Delete Files and Directories in Python: Using os.remove and shutil.rmtree

In file manipulation programs, deleting unnecessary temporary files or directories containing old data is often necessary.

In Python, the function used differs depending on whether the target is a “file” or a “directory (folder)”.

This article explains how to use os.remove() to delete files, shutil.rmtree() to delete entire directories, and provides precautions for safe deletion.

目次

1. Deleting a File: os.remove()

To delete a single file, use the remove() function from the standard os library.

Syntax:

import os

os.remove(file_path)

Specific Usage Example:

Here is an example of deleting a temporary file that is no longer needed after processing is complete.

import os

# File to delete
target_file = "temp_data.csv"

print(f"Target: {target_file}")

try:
    # Delete the file
    os.remove(target_file)
    print("File deleted.")

except FileNotFoundError:
    # Error handling if the file does not exist
    print("Error: File not found.")

except PermissionError:
    # Error handling if the file is open or locked
    print("Error: Permission denied (file might be in use).")

Execution Result (if the file exists):

Target: temp_data.csv
File deleted.

Points of Caution:

  • Cannot delete directories: If you specify a directory path in os.remove(), an IsADirectoryError (or PermissionError) will occur.
  • Does not go to the Recycle Bin: Files deleted with this function are permanently removed without going through the Recycle Bin. Restoration is difficult, so be careful when specifying paths.

2. Deleting an Empty Directory: os.rmdir()

If you want to delete a directory that is completely empty, use the os.rmdir() function.

import os

empty_dir = "empty_folder"

try:
    os.rmdir(empty_dir)
    print(f"Directory '{empty_dir}' deleted.")
except OSError as e:
    print(f"Could not delete: {e}")

If even a single file or subdirectory remains inside the directory, an OSError (directory not empty) will occur, and it cannot be deleted.

3. Deleting a Directory with Contents: shutil.rmtree()

To delete a directory along with all the files and subdirectories inside it, use the rmtree() function from the standard shutil library.

This is a powerful operation equivalent to the Unix command rm -rf.

Syntax:

import shutil

shutil.rmtree(directory_path)

Specific Usage Example:

Here is an example of deleting a directory full of cache files at once (cleanup).

import shutil
import os

# Directory to delete (can contain files)
cache_dir = "app_cache"

print(f"Starting deletion of '{cache_dir}'...")

if os.path.exists(cache_dir):
    try:
        # Delete the entire directory tree
        shutil.rmtree(cache_dir)
        print("Deletion complete.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
else:
    print("Directory to delete does not exist.")

Execution Result:

Starting deletion of 'app_cache'...
Deletion complete.

Like os.remove(), data deleted this way cannot be recovered. Since shutil.rmtree() wipes out large amounts of data instantly, it is recommended to carefully verify the target path using os.path.exists() before execution.

Summary

Choose the appropriate function based on what you want to delete:

  • Delete a file: os.remove(path)
  • Delete an empty directory: os.rmdir(path)
  • Delete a directory with contents: shutil.rmtree(path)
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次