-1

I want to do an os.path.join that contains a list in filenames because there are 3 files in that final folder. I want to only use the PST.shp

import os
fo = []
f = r'C:\Users\user\Desktop\folder\folder1'
for dirpath,dirnames,filenames in os.walk(f):      
        print(filenames)
        #fo.append(os.path.join(dirpath,filenames))

gives:

[]
[]
['PST.dbf', 'PST.shp', 'PST.shx']
[]
['PST.dbf', 'PST.shp', 'PST.shx']
[]
['PST.dbf', 'PST.shp', 'PST.shx']
[]
['PST.dbf', 'PST.shp', 'PST.shx']
[]

How to filter so I use only the PST.shp full path in the list fo?

something like:

 fo = []
    f = r'C:\Users\user\Desktop\folder\folder1'
    for dirpath,dirnames,filenames in os.walk(f):  
         if filenames not empty:    
            print(filenames)
            fo.append(os.path.join(dirpath,filenames[0][1]))

2 Answers2

0

Use endswith function to check for extensiton as follows,

for dirpath,dirnames,filenames in os.walk(f):  
   for f in filenames:
       if f.endswith('.shp'):
          fo.append(os.path.join(dirpath,f))
Oli
  • 1,313
  • 14
  • 31
0

If you are sure that you will only use the script to process a PST shape, just follow @AbdulNiyasPM's advice and check and process the PST.shp file:

     ...
     if filenames not empty:    
        print(filenames)
        if 'PST.shp' in filenames:
            fo.append(os.path.join(dirpath, 'PST.shp'))

If you want to keep any shp file, you can simple test that pattern:

     ...
     if filenames not empty:    
        print(filenames)
        for name in filenames:
            if name.endswith('.shp'):
                fo.append(os.path.join(dirpath, name))

Beware: if you need to be able to support non case sensitive platforms like Windows (ie: if you want to accept file names like xx.Shp or yy.SHP) a simple str.endswith is not enough, and you should use fnmatch or at least a non case sensitive regex (thanks to Peter Wood for his remark).

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • What if the filename is uppercase, `'PST.SHP'`? It would be safer to use [**`fnmatch`**](https://docs.python.org/3.1/library/fnmatch.html) as it deals with case based on operating system support. – Peter Wood Nov 19 '18 at 08:35