3

I have 2 shapefiles, each one placed in a different folder:

  • "C:\...\Folder O\Germany (O).shp"
  • "C:\...\Folder P\Germany Berlin (P).shp"

The following script finds the shapefiles and contains a couple of if conditions. The first if condition strips the "(O).shp" and "(P).shp" from the shapefiles. This works perfectly.

I want to set up a second if condition whereby the first name of both shapefiles matches, so in this case it would be "Germany". I thought the string.split method would be ideal but I'm clearly not implementing it correctly.

Could someone kindly point out my mistake please?

def run():
    for o in glob.glob("C:\Users\me\Desktop\Test\Folder O" + "\*.shp"):
        for p in glob.glob("C:\Users\me\Desktop\Test\Folder P" + "\*.shp"):
            if os.path.basename(o).rstrip("(O).shp") == os.path.basename(p).rstrip("(P).shp"):
                print p
                # works perfectly up to here

                if os.path.basename(o).split(o[[1]]) == os.path.basename(p).split(p[1]]):
                    print p

closed as off-topic by PolyGeo Apr 21 '15 at 20:00

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions about software development are off-topic here unless they relate directly to Geographical Information Systems, but they can be asked on Stack Overflow." – PolyGeo
If this question can be reworded to fit the rules in the help center, please edit the question.

6

Try the following:

if os.path.basename(o).split(' ')[0] == os.path.basename(p).split(' ')[0]:
    print p

This splits the basename where spaces (' ') occur, creating a list of string parts, and returns the item in the list at index 0 (the first item).

You would need to modify this to split at any other character (i.e. underscore, hyphen, etc)

  • 2
    ah! beat me by seconds! Also, Joseph, note that because of your earlier if statement, this if statement will always return True, because you are already comparing identical strings. – mr.adam Apr 21 '15 at 14:43
  • @Barbarossa - Brilliant and very insightful, Thank you very much! – Joseph Apr 21 '15 at 14:48
  • 1
    @mr.adam - Haha always fun when that happens! But thank you buddy for pointing the error with the first if statement, that is indeed what is happening so I will try and fix that! In fact, I think getting rid of the first if statement would work fine so again, many thanks! – Joseph Apr 21 '15 at 14:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.