Select to view content in your preferred language

Removing .shp from user output/Changing Name

1379
13
Jump to solution
10-09-2018 03:37 PM
AdamThompson3
New Contributor III

So I have created a tool that just mimics the Erase Tool but with a basic license, and the only problem I am running into is when the user selects the output as a shapefile, it messes with my file naming that I do with my processes such as intersect or union. The user is given 3 options to enter, inFc, EraseFc, and Outfc

For example;

ERROR 000732: Selecting Features: Dataset D:\PythonDataTest\ERASE_TESTT.shp_Intersect does not exist or is not supported
Failed to execute (SelectLayerByLocation).

As you can see it is trying to append the _Intersect behind the .shp of the output file name the user selected. And this of course wont work later on when my other processes try and find that shapefile.. SO

my question is how do I get the output name + the string im appending to it, to be before .shp and not after it.

Any help is appreciated thank you!

0 Kudos
13 Replies
DanPatterson_Retired
MVP Emeritus

prepare for python 3.

result = "{}_intersect{}".format(*x)  

"{0} whatever {1}"     means I can pass 2 things into this and it will convert those objects, of any kind, into strings.  with 'whatever' inbetween

In my example I knew that there were only going to be two objects, the left and right parts of splitting the file path, so the '0' and '1' can be omitted.

*x   means basically, unfold/unroll the pieces from 'x'  so you don't have to do explicit 'slicing' like x[0] and x[1]  

So I could have written 'result' as

(result = "{}_intersect{}".format(x[0], x[1]) 

 

The nice thing about starred expressions and formatters is that you don't need to know how may things are in a thing... you just do it.  For example

x = [1,2,3,4,5]
("{} "*len(x)).format(*x)
 '1 2 3 4 5 '

I have some blog posts on formatting in python.

AdamThompson3
New Contributor III

Thanks once again Dan, 

That definitely clarifies it up for me! Ill check out the blog posts

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

If working in Python 3.4+, you can also use 11.1. pathlib — Object-oriented filesystem paths — Python 3.4.9 documentation 

>>> import pathlib
>>> path = pathlib.Path(r"C:\tmp\folder\test.shp")
>>> print(path.with_suffix(""))
C:\tmp\folder\test
>>>
>>> path = pathlib.Path(r"C:\tmp\fgdb.gdb\test")
>>> print(path.with_suffix(""))
C:\tmp\fgdb.gdb\test
>>>
0 Kudos
DanPatterson_Retired
MVP Emeritus

There have been changes to os as well, which are now supported in pathlib

os — Miscellaneous operating system interfaces — Python 3.7.1rc1 documentation 

and additions to and modifications of pathlib occurred in 3.5, and 3.6

pathlib — Object-oriented filesystem paths — Python 3.7.1rc1 documentation 

0 Kudos