Search code examples
pythonfileconditional-statementsfile-typedelete-file

Delete files of given types IFF there are no other file types in folder


I want to delete certain files of type [cue,jpg,png,m3u,etc.] but if and only if they are in a folder by themselves or other files of [cue,jpg,png,m3u,etc.] type. I already have a function that can get me all the files of type [cue,jpg,png,m3u,etc.] in any given folder and return it as a list, but I just need to delete all of it according to the conditions above. To give an example: File q.jpg is in a folder by itself. After myfunc() finishes, it is deleted.

EDIT Sorry for unclearness. Let me give a better example: We have two folders, Alpha and Beta in folder Gamma. In Alpha, there are three files: 1.mp3, 2.mp3, folder.jpg. In Beta, there is one file cover.jpg. After myfunc() finishes, 1.mp3, 2.mp3, folder.jpg should be untouched while cover.jpg should be deleted.


Solution

  • It sounds like you have two steps:

    1) Given a list of extensions, get the list of all files in a folder matching that extension.

    2) If all the files in your directory have an extension matching your list, remove them

    Note that this doesn't include any information about how to traverse the directory structure, or which directories to test ... the sample code has a single directory hard-coded in.

    import os       
    
    dir = "myDirectory" 
    extList = ['ext1', 'ext2', 'ext3']
    allfiles = os.listdir(dir) # all files in that directory
    
    myfiles = [] # will be appended to to only contain files with extensiosn matching extlist
    for file in allfiles:
        parts = file.split('.') # split the filename based on .
        if parts[-1] in extensionlist:
            myfiles.append(file) 
    
    if len(myfiles) == len(allfiles):
        for file in myfiles:
            path = "%s/%s" % (dir, file)
            os.remove(path)
            os.remove(file)