Question

The code tries to find that which files are empty and which files are not and print a list of filenames with their status(empty/not empty).

import fnmatch
import os
import pprint

#filenames_dic= {}
v = []

for root, dirnames, filenames in os.walk('P:/data/'):
    for filename in fnmatch.filter(filenames, '*.txt'):

        address=os.path.join(root,filename)
        size= os.path.getsize(address)
        if (size == 0):
            status= ('EMPTY')          

        else:
            status = (size)

        v.append([address,status])
Was it helpful?

Solution

number_of_empty_files = len([x[1] for x in v if x[1] == 'EMPTY'])

or

number_of_empty_files = len(filter(lambda x: x[1] == 'EMPTY', v))

OTHER TIPS

If you want to iterate over the list again to get the number of empty files, then you could do as Ellochka Cannibal suggested, though that is rather wasteful if you're only counting the files. To get the count, you could simply put a counter variable in your if statement:

c=0
...
for ...
  if (size == 0):
    status = ('EMPTY') 
    c += 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top