How To Delete and Remove File and Directory with Python?
Python provides different methods and functions in order to remove files and directories. As python provides a lot of functionalities we can remove files and directories according our needs. For example we can remove files those sizes are bigger than 1 MB.
Remove File with remove
We can use
os.remove() function in order to remove file. We should import the
os module in order to use
remove function. In this example we will remove file named
Remove File with unlink
unlink is used to remove files.
unlink implements exact mechanisms of the
unlinkis defined because of to implement
Unix philosophy. Look
remove for more information.
Remove Empty Directory with rmdir
As we know Linux provides
rmdir command which used to remove empty directories. Python provides same function under
os module. We can only delete empty directories with
Delete Directory and Contents Recursively with rmtree
How can we delete directory and its contents. We can not use
rmdir because directory is not empty. We can use
Delete Only Specific File Types or Extensions
While deleting files we may require only delete specific file types or extensions. We can use
* wildcard in order to specify file extensions. For example in order to delete
text files we can specify the
*.txt extension. We should also use
glob module and function to create list of files.
In this example we will list all files with extensions
.txt by using
glob function. We will use list name
filelist for these files. Then loop over the list to remove files with
remove() function one by one.
for file in filelist: