import os class FileData: def __init__(self, name, path): self.name = name self.path = path # 遍历项目文件夹中的所有图片文件 image_files = [] def get_all_image_files(folder): for root, dirs, files in os.walk(folder): for file in files: if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg") or file.endswith(".gif"): filenew1 = FileData(file, os.path.join(root, file)) image_files.append(filenew1) for dir in dirs: get_all_image_files(os.path.join(root, dir)) return # 在代码文件中搜索图片文件的引用 referenced_files = [] def search_image_references(image_files, code_folder): for root, dirs, files in os.walk(code_folder): for file in files: if file.endswith(".vue") or file.endswith(".css") or file.endswith(".js"): with open(os.path.join(root, file), 'r', encoding='utf-8') as f: content = f.read() for image_file in image_files: if image_file.name in content: if(image_file.name not in referenced_files): referenced_files.append(image_file.name) for dir in dirs: search_image_references(image_files, os.path.join(root, dir)) return # 找出没有被引用的图片文件 def find_unused_images(all_images, referenced_images): unused_images=[] for image in all_images: if(image.name not in referenced_images): if os.path.exists(image.path): os.remove(image.path) print(f"文件 {image.name} 删除成功") return unused_images # 主函数 def main(): project_folder = "图片资源路径" code_folder = "代码路径" get_all_image_files(project_folder) search_image_references(image_files, code_folder) unused_images = find_unused_images(image_files, referenced_files) print("Unused images:") if __name__ == "__main__": main()
标签:脚本,files,name,前端,中未,file,images,path,image From: https://www.cnblogs.com/huangqiang0208/p/17947423