Skip to content

Instantly share code, notes, and snippets.

@ddrigass
Last active August 7, 2020 10:56
Show Gist options
  • Save ddrigass/5df1b85873f6551ed6265c31a2170ff2 to your computer and use it in GitHub Desktop.
Save ddrigass/5df1b85873f6551ed6265c31a2170ff2 to your computer and use it in GitHub Desktop.
Python 3 script to remove unused files. Example: remove old pictures from a project.
import os
dirName = '/home/dir/project'
imageFormats = ['.png', '.jpeg', '.gif', '.svg', '.jpg']
imagesIgnore = ['node_modules', 'build']
sourceIncludes = ['.js', '.php', '.html']
sourceIgnore = ['node_modules', 'build']
def getListOfFiles(dirName, includeList, excludingList):
listOfFile = os.listdir(dirName)
allFiles = list()
for entry in listOfFile:
fullPath = os.path.join(dirName, entry)
if os.path.isdir(fullPath):
allFiles = allFiles + getListOfFiles(fullPath, includeList, excludingList)
elif any(x in fullPath for x in includeList) and not(any(x in fullPath for x in excludingList)):
allFiles.append(fullPath)
return allFiles
def fileHasString(filePath, string):
with open(filePath) as f:
filecontent = f.read()
return string in filecontent
listOfImages = getListOfFiles(dirName, imageFormats, imagesIgnore)
listOfSourceFiles = getListOfFiles(dirName, sourceIncludes, sourceIgnore)
listOfActiveImages = list()
for filePath in listOfSourceFiles:
for imagePath in listOfImages:
string = os.path.basename(imagePath)
has = fileHasString(filePath, string)
if has and imagePath not in listOfActiveImages: listOfActiveImages.append(imagePath)
listOfDisactiveImages = list()
for image in listOfImages:
if image not in listOfActiveImages: listOfDisactiveImages.append(image)
for imagePath in listOfDisactiveImages:
print(imagePath)
# os.remove(imagePath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment