作为Android开发,需要删除res目录下没有用到的图片,但工程太大,图片太多,若是一个个对比,太费时间了,所以借用Python来筛选没有用到的图片,进而删除。代码如下:
import os # 查找目录下没有用到的drawable图片,并删除 def findDrawable(path): # 项目位置 filePath = "F:/workspace/Android/app/src/main" # 搜索关键词 keyWord = ["R.drawable.","@drawable/","R.mipmap.","@mipmap/"] # 存在图片的目录 dirs1 = ["drawable-hdpi\\","drawable-mdpi\\","drawable-ldpi\\","drawable-xhdpi\\","drawable-xxhdpi\\", "drawable-xxxhdpi\\","drawable\\", "mipmap-hdpi\\","mipmap-mdpi\\","mipmap-xhdpi\\", "mipmap-xxhdpi\\", "mipmap-xxxhdpi\\"] strings = [] # 记录drawable文件夹下的XML文件名(不带路径) stringXmlDrawable = [] # 记录所有的图片(全路径名) stringDrawable = [] with open(path, 'a', encoding='utf-8') as wf: # 遍历当前目录 for root, dirs, files in os.walk(filePath): # 遍历文件 for file in files: # pathFiles 是路径+文件名=绝对路径数组 pathFiles = os.path.join(root, file) # 查找drawable目录下的xml文件 if ".xml" in pathFiles and "drawable" in pathFiles: str = pathFiles.split(".xml")[0]; for dir in dirs1: if dir in str: stringXmlDrawable.append(str.split(dir)[1]) break if ".xml" not in pathFiles and ("drawable" in pathFiles or "mipmap" in pathFiles): stringDrawable.append(pathFiles) if ".java" in pathFiles or ".xml" in pathFiles: # 读取每个文件 with open(pathFiles, 'r', encoding='utf-8') as w: # 读取文件的每一行 for lines in w: for key in keyWord: if key in lines: str = lines.split(key)[1] if ")" in str: str = str.split(")")[0] if ";" in str: str = str.split(";")[0] if "," in str: str = str.split(",")[0] if "\"" in str: str = str.split("\"")[0] if "<" in str: str = str.split("<")[0] if str not in strings: strings.append(str) for s in stringDrawable: s1 = s.split(".")[0] for dir in dirs1: if dir in s1: s1 = s1.split(dir)[1] if s1 not in stringXmlDrawable and s1 not in strings: # 将没有用到的图片写入文件中,并且避免重复写入 wf.write(s1) wf.write("\n") # 真正的删除操作 os.remove(s) if __name__ == '__main__': path = "E:/text/Content.txt" findDrawable(path)初学Python,请多指教。