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

阅读 38

2022-04-18

需求提出

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

解决思路

参考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)

0 0 举报