I have a function called USB()
, that will observe a USB stick's insertion and delete files inside of it, if there are some:
import os
import shutil
# 1. Check and clean USB
def USB():
usb_inserted = os.path.isdir("F:") # <-- returns boolean...checks whether a directory exists
if usb_inserted == False:
print("\n\nUSB stick is not plugged in. Waiting for connection...")
while usb_inserted == False: # wait
""" updating variable, because it takes only the return value of function 'isdir()'
and stays the same regardless of the fact, that 'isdir()' changed """
usb_inserted = os.path.isdir("F:")
continue
SECURITY_FILE = "System Volume Information"
if os.listdir("F:") == [SECURITY_FILE] or os.listdir("F:") == []: # if list of files contains only the security file (is empty)
print("\nUSB flash is already empty.") # send a message and continue
else:
files = os.listdir("F:") # list of names of files in the usb flash, that will be deleted
if SECURITY_FILE in files:
""" taking out the security file from the list, because attempting to delete it causes
'PermissionError [WinError 5]' exception """
files.remove(SECURITY_FILE)
for file in files: # Loop through the file list
if os.path.isfile(f"F:\\{file}"): # if it's a file
os.remove(f"F:\\{file}") # Delete the file
elif os.path.isdir(f"F:\\{file}"): # if it's a directory/folder
shutil.rmtree(f"F:\\{file}") # remove the folder
print("\nAll files/folders are deleted from USB.")
USB()
Is there anything, that can be improved in terms of cleaner code or things that I could have missed while testing?