Vogelsire
Vogelsire

Reputation: 189

How to compare a list and directory to check for missing files?

I have a folder /image/ that has the following files: 1.jpg, 2.jpg, 5.jpg

And a list:

img = [1.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg]

How do I compare the list and the directory contents to find out that 3.jpg and 4.jpg files are missing?

I searched online but the only solutions I found show how to compare list to list or directory to directory.

Upvotes: 2

Views: 4365

Answers (3)

Udo Klein
Udo Klein

Reputation: 6882

import os
path= r"C:\yourdirectory"  
fileList = os.listdir(path)

img = [...]
missing = [name for name in img if name not in fileList]

If order is not important you can use sets instead

import os
path= r"C:\yourdirectory"  
fileSet = set(os.listdir(path))

img = [...]
missing = set(img)-fileSet

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174622

To search for files in a directory, you can use glob, like this:

import glob

dir_to_search = '/some/path/to/images/'

files_in_dir = glob.glob("{}{}".format(dir_to_search,'*.jpg'))

list_of_files = ['1.jpg','2.jpg','3.jpg']

missing_files = [x for x in list_of_files if x not in files_in_dir]

Upvotes: 3

masterofdestiny
masterofdestiny

Reputation: 2811

What about this .

Get all file extension first from a file

import os
createlist = []
for r,d,f in os.walk("/images"):
    for files in f:
        if files.endswith(".jpg"):
             createlist.append[files]

And then compare both list like.

print [(i,j) for i,j in zip(img,createlist) if i!=j]

Upvotes: 1

Related Questions