How To Delete and Remove File and Directory with Python?

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/delete-and-remove-file-and-directory-with-python/
PINTEREST
PINTEREST
INSTAGRAM

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 trash.

Remove File with remove

Remove File with remove

Remove File with unlink

unlink is used to remove files. unlink implements exact mechanisms of the remove . 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 rmdir.

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 shutil module rmtree function.

Delete Directory and Contents Recursively with rmtree

Delete Directory and Contents Recursively with rmtree

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.

LEARN MORE  Git - File Operations

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.

Delete Only Specific File Types or Extensions

Delete Only Specific File Types or Extensions

Remove

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/delete-and-remove-file-and-directory-with-python/
PINTEREST
PINTEREST
INSTAGRAM

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)