0
点赞
收藏
分享

微信扫一扫

【Python】判断是否有该文件或文件夹然后进行删除

何晓杰Dev 2022-04-18 阅读 38

需求提出

在处理项目开源中需要将一些没有开源价值的文件进行删除或者替代。

解决思路

参考Python判断文件、目录是否存在的三种方法

#文件判断
if os.access(os.path.join(source_demo_root_path, "app/build"), os.F_OK):
	delete(os.path.join(source_demo_root_path, "app/build"))
# 文件删除:
def delete(path):
    """
    删除一个文件/文件夹
    :param path: 待删除的文件路径
    :return:
    """
    if not os.path.exists(path):
        print ("[*] {} not exists".format(path))
        return

    if os.path.isdir(path):
        shutil.rmtree(path)
    elif os.path.isfile(path):
        os.remove(path)
    elif os.path.islink(path):
        os.remove(path)
    else:
        print ("[*] unknow type for: " + path)
举报

相关推荐

0 条评论