os.unlink()

Deletes a file permanantly

In [1]:
import os
In [2]:
os.listdir('F:\\Example')
Out[2]:
['somenewfile.txt']
In [3]:
os.unlink('F:\\Example\\somenewfile.txt')
In [4]:
os.listdir('F:\\Example')
Out[4]:
[]


os.rmdir()

Deletes a folder permanantly
os.rmdir() only works when the folder is completely empty. Now, since the only file in the F:\Example folder was deleted with os.unlink(), the directory 'Example' can be deleted with os.rmdir()

In [5]:
os.rmdir('F:\\Example')


shutil.rmtree

Deletes a folder permanantly and its entire contents
Kind of like a delete analogue of shutil.copytree()

In [6]:
import shutil
In [7]:
shutil.rmtree('F:\\Example2')


These functions deletes the files/directories without sending to the recycle bin/trash. So these functions should be used really carefully


Dry Run

In the dry run, the code that deletes something is commented out.

Let's say I want to delete all the text files in the folder, but instead of typing .txt I accidently typed .rxt

In [8]:
os.chdir('F:\\Example3')                    #changing the current working directory

for filename in os.listdir():
    if filename.endswith('.rxt'):
        #os.unlink(filename)
        print(filename)

After looking at the output, I realise I was going to delete the very important file, so I rewrite the code now correcting .rxt to .txt, commenting out the print and uncommenting the os.unlink()

In [9]:
os.chdir('F:\\Example3')                    #changing the current working directory

for filename in os.listdir():
    if filename.endswith('.txt'):
        os.unlink(filename)
        #print(filename)

Above code deleted all the txt files.



send2trash Module

Instead of deleting permanantly, this module will send it to the trash of the operating system.

It doesn't come with python so it needs to be installed with the pip installer. It can be installed on windows by opening command prompt and typing the following
pip install send2trash

In [10]:
import send2trash

send2trash has function send2trash which can send to trash the file/directory which is passed to it.

In [11]:
send2trash.send2trash('VERY_IMPORTANT_FILE.rxt')
#using relative path since the cwd is changed to F:\\Example3 and the file is in the folder F:\Example3

And the very important file is in recycle bin.



-os.unlink() will delete a file

-os.rmdir() will delete an empty folder.

-shutil.rmtree() will delete a folder and all its contents

-Deleting can be dangerous, so do a dry run first

-send2trash.send2trash() will send a file or folder to the recycle bin.