Kelsey Jimerson
Kelsey Jimerson

Reputation: 1

In Python how do I search for and count/print a specific set of characters in each item/string in a list

I need to eventually display all the items in my list that have the file ending .shp. So I need to be able to index each list item separately. Any suggestions?

This is what I have so far:

folderPath = r'K:\geog 173\LabData'

import os
import arcpy

arcpy.env.workspace = (folderPath)
arcpy.env.overwriteOutput = True

fileList = os.listdir(folderPath)
print fileList


"""Section 2: Identify and Print the number
and names of all shapefiles in the file list:"""

numberShp = 0

shpList= list()

for fileName in fileList:
    print fileName

fileType = fileName[-4:]
print fileType

if fileType == '.shp':
    numberShp +=1
    shpList.append(fileName)

print shpList
print numberShp

Upvotes: 0

Views: 95

Answers (2)

Sravan K Ghantasala
Sravan K Ghantasala

Reputation: 1338

Can You Please specify the desired output format. That would make the job easy...

One Probable Answer would be

fileList = [f for f in os.listdir('K:\geog 173\LabData') if f.endswith('.shp')]

for i,val in enumerate(fileList):
    print '%d. %s' %(i,val)  

#If u want to print the length of the list again...
print len(fileList)  

Upvotes: 0

grc
grc

Reputation: 23575

You could do this quite easily with list comprehensions and str.endswith():

shpList = [fileName for fileName in fileList if fileName.endswith('.shp')]

print shpList
print len(shpList)

Upvotes: 1

Related Questions