How to delete a file or folder?

前端 未结 13 1109
青春惊慌失措
青春惊慌失措 2020-11-22 12:29

How do I delete a file or folder in Python?

相关标签:
13条回答
  • 2020-11-22 13:22

    For deleting files:

    os.unlink(path, *, dir_fd=None)
    

    or

    os.remove(path, *, dir_fd=None)
    

    Both functions are semantically same. This functions removes (deletes) the file path. If path is not a file and it is directory, then exception is raised.

    For deleting folders:

    shutil.rmtree(path, ignore_errors=False, onerror=None)
    

    or

    os.rmdir(path, *, dir_fd=None)
    

    In order to remove whole directory trees, shutil.rmtree() can be used. os.rmdir only works when the directory is empty and exists.

    For deleting folders recursively towards parent:

    os.removedirs(name)
    

    It remove every empty parent directory with self until parent which has some content

    ex. os.removedirs('abc/xyz/pqr') will remove the directories by order 'abc/xyz/pqr', 'abc/xyz' and 'abc' if they are empty.

    For more info check official doc: os.unlink , os.remove, os.rmdir , shutil.rmtree, os.removedirs

    0 讨论(0)
提交回复
热议问题