How to Delete Files and Directories in Python - MS TV Life.COM

How to Delete Files and Directories in Python

How to Delete Files and Directories in Python

Python has a number of built-in modules that assist you to delete information and directories.

How To Make Your Blog Secure and Safe

This tutorial explains how one can delete information and directories utilizing capabilities from the os, pathlib, and shutil modules.

Deleting Information #

In Python you should use os.take away(), os.unlink(), pathlib.Path.unlink() to delete a single file.

The os module supplies a transportable means of interacting with the working system. The module is offered for each Python 2 and three.

To delete a single file with os.take away(), go the trail to the file as an argument:

import os

file_path = '/tmp/file.txt'
os.take away(file_path)

os.take away() and os.unlink() capabilities are semantically an identical:

import os

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

If the required file doesn’t exist a FileNotFoundError error is thrown. Each os.take away() and os.unlink() can delete solely information, not directories. If the given path factors to a listing, they are going to trow IsADirectoryError error.

Deleting a file requires a write and execute permission on the listing containing the file. In any other case, you’re going to get PermissionError error.

To keep away from errors when deleting information, you should use exception dealing with to catch the exception and ship a correct error message:

import os

file_path = '/tmp/file.txt'

attempt:
    os.take away(file_path)
besides OSError as e:
    print("Error: %s : %s" % (file_path, e.strerror))

The pathlib module is offered in Python 3.four and above. If you wish to use this module in Python 2 you’ll be able to set up it with pip. pathlib supplies an object-oriented interface for working with filesystem paths for various working programs.

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

from pathlib import Path

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

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

pathlib.Path.unlink(), os.take away(), and os.unlink() will also be used to delete a symlink.

Sample matching #

You need to use the glob module to match a number of information primarily based on a sample. For instance, to take away all .txt information within the /tmp listing, you’ll use one thing like this:

import os
import glob

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

for f in information:
    attempt:
        f.unlink()
    besides OSError as e:
        print("Error: %s : %s" % (f, e.strerror))

To recursively delete information all .txt within the /tmp listing and all subdirectories beneath it, the go the recursive=True argument to the glob() operate and use the “**` sample:

import os
import glob

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

for f in information:
    attempt:
        os.take away(f)
    besides OSError as e:
        print("Error: %s : %s" % (f, e.strerror))

The pathlib module contains two glob capabilities, glob() and rglob() to match information in a given listing. glob() matches information solely within the prime stage listing. rglob() matches all information within the listing and all subdirectories, recursively. The next instance code deletes all .txt information within the /tmp listing:

from pathlib import Path

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

Deleting Directories (Folders) #

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

The next instance exhibits how one can take away an empty listing:

import os

dir_path = '/tmp/img'

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

Alternatively, you’ll be able to delete directories with the pathlib module:

from pathlib import Path

dir_path = Path('/tmp/img')

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

The shutil module lets you carry out quite a few high-level operations on information and directories.

With the shutil.rmtree() operate you’ll be able to delete a given listing together with its content material:

import shutil

dir_path = '/tmp/img'

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

The argument handed to shutil.rmtree() can’t be a symbolic hyperlink to a listing.

Conclusion #

Python supplies a number of modules for dealing with information.

We’ve proven you how one can use os.take away(), os.unlink(), pathlib.Path.unlink() to delete a single file, os.rmdir() and pathlib.Path.rmdir() to delete an empty listing and shutil.rmtree() to recursively delete a listing and all of it’s contents.

Be additional cautious when eradicating information or directories, as a result of as soon as the file is deleted, it can’t be simply recovered.

12 Best Related Post WordPress Plugins

If in case you have any questions or suggestions, be at liberty to go away a remark.

Copy link
Powered by Social Snap