YouTube Icon

Code Playground.

How to Delete (Remove) Files and Directories in Python

CFG

How to Delete (Remove) Files and Directories in Python

Python has a couple of implicit modules that permit you to erase records and indexes. 

This instructional exercise discloses how to erase records and indexes utilizing capacities from the os, pathlib, and shutil modules. 

Deleting Files

In Python you can utilize os.remove(), os.unlink(), pathlib.Path.unlink() to erase a solitary record. 

The os module furnishes a compact method of communicating with the working framework. The module is accessible for both Python 2 and 3. 

To erase a solitary record with os.remove(), pass the way to the document as a contention: 

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)

On the off chance that the predetermined record doesn't exist a FileNotFoundError blunder is tossed. Both os.remove() and os.unlink() can erase just documents, not indexes. On the off chance that the given way focuses to an index, they will trow IsADirectoryError blunder. 

Erasing a record requires a compose and execute consent on the index containing the document. Else, you will get PermissionError blunder. 

To keep away from mistakes when erasing documents, you can utilize exemption taking care of to get the special case and send an appropriate blunder 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 accessible in Python 3.4 or more. In the event that you need to utilize this module in Python 2 you can introduce it with pip. pathlib gives an article arranged interface to working with filesystem ways for various working frameworks. 

To erase a record with thepathlib module, make a Path object highlighting the document and call the unlink() strategy on the article: 

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 likewise be utilized to erase a symlink . 

Pattern matching

You can utilize the glob module to coordinate different records dependent on an example. For instance, to eliminate all .txt records in the/tmp index, you would utilize 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 erase documents all .txt in the/tmp registry and all subdirectories under it, the pass the recursive=True contention to the glob() capacity and utilize the ''**' design: 

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 incorporates two glob capacities, glob() and rglob() to coordinate documents in a given catalog. glob() matches records just in the high level catalog. rglob() coordinates all records in the catalog and all subdirectories, recursively. The accompanying model code erases all .txt records in the/tmp catalog: 

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 utilize os.rmdir() and pathlib.Path.rmdir() to erase an unfilled catalog and shutil.rmtree() to erase a non-void registry. 

The accompanying model tells the best way to eliminate an unfilled registry: 

import os

dir_path = '/tmp/img'

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

Then again, you can erase catalogs 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 permits you to play out various elevated level procedure on documents and indexes. 

With the shutil.rmtree() work you can erase a given catalog including its substance: 

import shutil

dir_path = '/tmp/img'

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

The contention passed to shutil.rmtree() can't be an emblematic connect to an index. 

Conclusion

Python gives a few modules to dealing with records. 

We've told you the best way to utilize os.remove(), os.unlink(), pathlib.Path.unlink() to erase a solitary record, os.rmdir() and pathlib.Path.rmdir() to erase an unfilled index and shutil.rmtree() to recursively erase a registry and every last bit of it's substance. 

Be extra cautious when eliminating records or catalogs, on the grounds that once the document is erased, it can't be handily recouped. 

In the event that you have any inquiries or input, don't hesitate to leave a remark.




CFG