0

The following python code counts the number of total files I have in a directory which contains multiple subdirectories. The result prints the subdirectory name along with the number of files it contains.

How can I modify this so that:

  • It only looks for a specific file extension (i.e. "*.shp")
  • It provides both the number of ".shp" files in each subdirectory and a final count of all ".shp" files

Here is the code:

import os
path = 'path/to/directory'
folders = ([name for name in os.listdir(path)])
for folder in folders:
    contents = os.listdir(os.path.join(path,folder))
    print(folder,len(contents))
Joseph
  • 586
  • 1
  • 13
  • 32

2 Answers2

1

you can use the .endswith() function on strings. This is handy for recognizing extensions. You could loop through the contents to find these files then as follows.

targets = []
for i in contents:
    if i.endswith(extension):
        targets.append(i)
print(folder, len(contents))
user7296055
  • 105
  • 3
0

Thanks for the comments and answer, this is the code I used (feel free to flag my question as a duplicate of the linked question if it is too close):

import os
path = 'path/to/directory'
folders = ([name for name in os.listdir(path)])
targets = []
for folder in folders:
    contents = os.listdir(os.path.join(path,folder))
    for i in contents:
        if i.endswith('.shp'):
            targets.append(i)
    print(folder, len(contents))

print "Total number of files = " + str(len(targets))
Joseph
  • 586
  • 1
  • 13
  • 32
  • I would have started with *os..path.walk()* function and *os.path.splitext()* is cleaner than *endswith()*. – guidot Dec 14 '16 at 11:06
  • @guidot - Thanks for your comment, but why would _os.path.splitext()_ be cleaner than _endswith()_? – Joseph Dec 14 '16 at 11:09
  • 1
    Since a) you explicitly state, that you want to compare the extension instead of hiding this in a string b) less side effects if a file exists named *.shp* (unix-style name starting with dot, no extension intended). – guidot Dec 14 '16 at 11:16
  • @guidot - Thanks for your tip, I'll try and implement that =) – Joseph Dec 14 '16 at 11:24