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)
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)
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
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.print() and commented functions. send2trash.send2trash() will send a file or folder to the recycling bin.