Lesson 33:

Deleting Files

There are three typical functions delete files.

After moving into /files:


In [1]:
import os 
# Define base directory
defaultpath = os.path.expanduser('~/Dropbox/learn/books/Python/AutomateTheBoringStuffWithPython')

#Change directory to files directory if set in default 
if (os.getcwd() == defaultpath):
       os.chdir('/files')   
else:
    os.chdir(defaultpath + '/files')

import os and use unlink() to delete a file:


In [3]:
import shutil # import shutil for testing

shutil.copy('bacon.txt', 'bacon2.txt') # Copy file to with a new name

os.unlink('bacon2.txt') # Deletes a file

os.rmdir() can delete folders, but only empty folders.


In [5]:
os.rmdir('newerfiles') # Attempt to delete a directory (if empty)


---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-5-bf4c1fdbff70> in <module>()
----> 1 os.rmdir('newerfiles') # Attempt to delete a directory (if empty)

OSError: [Errno 66] Directory not empty: 'newerfiles'

shutil hasa rmtree() function, which is the inverse of the copytree() function.


In [18]:
if (os.path.exists(os.path.abspath('newerfiles')) != True):
    shutil.copytree('newfiles', 'newerfiles')

shutil.rmtree('newerfiles') # Deletes entire folder tree

Since these deletions are permanent, it is useful to run these programs in 'dry-run' mode; where the deletions/functions are commented, and print() is used instead:


In [26]:
import os

#Change directory to files directory if set in default 
if (os.getcwd() == defaultpath):
       os.chdir('/files')   
else:
    os.chdir(defaultpath + '/files')

# Move into the newfiles directory
os.chdir('newfiles')
         
for filename in os.listdir():
    if filename.endswith('.txt'):
        #os.unlink(filename)
        print(filename)


bacon.txt
bacon3.txt

All these deletions are permanent, but the send2trash module can be used to send deletions to the trash.


In [30]:
import send2trash # install via pip3

send2trash.send2trash(os.path.abspath('newfiles/bacon3.txt')) # Delete by snding to trash


---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-30-bfda7da4d52a> in <module>()
      1 import send2trash # install via pip3
      2 
----> 3 send2trash.send2trash(os.path.abspath('newfiles/bacon3.txt')) # Delete by snding to trash

/usr/local/lib/python3.5/site-packages/send2trash/plat_osx.py in send2trash(path)
     43     opts = kFSPathMakeRefDoNotFollowLeafSymlink
     44     op_result = FSPathMakeRefWithOptions(path, opts, byref(fp), None)
---> 45     check_op_result(op_result)
     46     opts = kFSFileOperationDefaultOptions
     47     op_result = FSMoveObjectToTrashSync(byref(fp), None, opts)

/usr/local/lib/python3.5/site-packages/send2trash/plat_osx.py in check_op_result(op_result)
     35     if op_result:
     36         msg = GetMacOSStatusCommentString(op_result).decode('utf-8')
---> 37         raise OSError(msg)
     38 
     39 def send2trash(path):

OSError: File not found

Recap

  • os.unlink() will permanently delete a file.
  • os.rmdir() will delete a folder (but the folder must be empty).
  • shutil.rmtree() will delete a folder and all its contents.
  • Deleting can be dangerous, so do a dry run first with print() and commented functions.
  • send2trash.send2trash() will send a file or folder to the recycling bin.