import os
os.listdir('F:\\Example')
os.unlink('F:\\Example\\somenewfile.txt')
os.listdir('F:\\Example')
os.rmdir('F:\\Example')
import shutil
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
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
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()
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.
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 followingpip install send2trash
import send2trash
send2trash has function send2trash which can send to trash the file/directory which is passed to it.
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.