Home  »  CodeSnippets   »   How to Delete a File or Folder in Python

How to Delete a File or Folder in Python

Posted: February 6, 2022 | by Michael Bright

Using os remove to remove a file:

import os
os.remove('/path/to/filename.txt')

Using os system to remove a file:

import os
os.system(f"rm -rf {filename.txt}")

Using os rmdir to remove an empty directory:

import os
os.rmdir('/path/to/folder/')

Using shutil rmtree to delete a directory and all its contents:

import shutil
shutil.rmtree('/your/folder/path/')

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.