How to delete a file or folder?

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

How do I delete a file or folder in Python?

13条回答
  •  清歌不尽
    2020-11-22 13:04

    Here is a robust function that uses both os.remove and shutil.rmtree:

    def remove(path):
        """ param  could either be relative or absolute. """
        if os.path.isfile(path) or os.path.islink(path):
            os.remove(path)  # remove the file
        elif os.path.isdir(path):
            shutil.rmtree(path)  # remove dir and all contains
        else:
            raise ValueError("file {} is not a file or dir.".format(path))
    

提交回复
热议问题