How to Delete (Remove) Files and Directories in Python

[ad_1]

Python has a few built-in modules that allow you to delete files and directories.

This tutorial explains how to delete files and directories using functions from the os, pathlib, and shutil modules.

Deleting Files #

In Python you can use os.remove(), os.unlink(), pathlib.Path.unlink() to delete a single file.

The os
module provides a portable way of interacting with the operating system. The module is available for both Python 2 and 3.

To delete a single file with os.remove(), pass the path to the file as an argument:

import os

file_path = '/tmp/file.txt'
os.remove(file_path)

os.remove() and os.unlink() functions are semantically identical:

import os

file_path = '/tmp/file.txt'
os.unlink(file_path)

If the specified file doesn’t exist
a FileNotFoundError error is thrown. Both os.remove() and os.unlink() can delete only files, not directories. If the given path points to a directory, they will trow IsADirectoryError error.

Deleting a file requires a write and execute permission on the directory containing the file. Otherwise, you will get PermissionError error.

To avoid errors when deleting files, you can use exception handling to catch the exception and send a proper error message:

import os

file_path = '/tmp/file.txt'

try:
    os.remove(file_path)
except OSError as e:
    print("Error: %s : %s" % (file_path, e.strerror))

The pathlib
module is available in Python 3.4 and above. If you want to use this module in Python 2 you can install it with pip. pathlib provides an object-oriented interface for working with filesystem paths for different operating systems.

To delete a file with thepathlib module, create a Path object pointing to the file and call the unlink() method on the object:

from pathlib import Path

file_path = Path('/tmp/file.txt')

try:
    file_path.unlink()
except OSError as e:
    print("Error: %s : %s" % (file_path, e.strerror))

pathlib.Path.unlink(), os.remove(), and os.unlink() can also be used to delete a symlink
.

Pattern matching #

You can use the glob
module to match multiple files based on a pattern. For example, to remove all .txt files in the /tmp directory, you would use something like this:

import os
import glob

files = glob.glob('/tmp/*.txt')

for f in files:
    try:
        f.unlink()
    except OSError as e:
        print("Error: %s : %s" % (f, e.strerror))

To recursively delete files all .txt in the /tmp directory and all subdirectories under it, the pass the recursive=True argument to the glob() function and use the “**` pattern:

import os
import glob

files = glob.glob('/tmp/**/*.txt', recursive=True)

for f in files:
    try:
        os.remove(f)
    except OSError as e:
        print("Error: %s : %s" % (f, e.strerror))

The pathlib module includes two glob functions, glob() and rglob() to match files in a given directory. glob() matches files only in the top level directory. rglob() matches all files in the directory and all subdirectories, recursively. The following example code deletes all .txt files in the /tmp directory:

from pathlib import Path

for f in Path('/tmp').glob('*.txt'):
    try:
        f.unlink()
    except OSError as e:
        print("Error: %s : %s" % (f, e.strerror))

Deleting Directories (Folders) #

In Python you can use os.rmdir() and pathlib.Path.rmdir() to delete an empty directory and shutil.rmtree() to delete a non-empty directory.

import os

dir_path = '/tmp/img'

try:
    os.rmdir(dir_path)
except OSError as e:
    print("Error: %s : %s" % (dir_path, e.strerror))

Alternatively, you can delete directories with the pathlib module:

from pathlib import Path

dir_path = Path('/tmp/img')

try:
    dir_path.rmdir()
except OSError as e:
    print("Error: %s : %s" % (dir_path, e.strerror))

The shutil
module allows you to perform a number of high-level operations on files and directories.

With the shutil.rmtree() function you can delete a given directory including its content:

import shutil

dir_path = '/tmp/img'

try:
    shutil.rmtree(dir_path)
except OSError as e:
    print("Error: %s : %s" % (dir_path, e.strerror))

The argument passed to shutil.rmtree() cannot be a symbolic link to a directory.

Conclusion #

Python provides several modules for handling files.

We’ve shown you how to use os.remove(), os.unlink(), pathlib.Path.unlink() to delete a single file, os.rmdir() and pathlib.Path.rmdir() to delete an empty directory and shutil.rmtree() to recursively delete a directory and all of it’s contents.

Be extra careful when removing files or directories, because once the file is deleted, it cannot be easily recovered.

If you have any questions or feedback, feel free to leave a comment.

[ad_2]

Source link

Related Posts

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.