Incorporate one variable into another in ArcPy Script

3550
4
Jump to solution
06-12-2015 05:44 AM
MeredithGreen
New Contributor III

I am trying to take a bunch of text files and export them to a workspace geodatabase and then take the new tables and do a summary stats calculation and export that out as a new table that is whatever the loss table is plus summ at the end.  Script is below.  What exactly is the best way to do this with a variable?  Any help would be greatly appreciated.

for file in arcpy.ListFiles("*.txt"):

    loss_table = os.path.join(output_workspace, str(file[:-4]))

    summary = os.path.join(output_workspace, str(loss_table + "summ"))

    arcpy.TableToGeodatabase_conversion(file, output_workspace)

    arcpy.Statistics_analysis(loss_table, summary, stats, "CensusBlock")

0 Kudos
1 Solution

Accepted Solutions
SepheFox
Frequent Contributor

Hi Meredith, Right now, you're joining your output workspace path to the summary path twice. Try just removing the output workspace from summary. I'm assuming, of course, that you have your other variables, such as output_workspace and stats, defined in a different part of the script.

View solution in original post

4 Replies
SepheFox
Frequent Contributor

Hi Meredith, Right now, you're joining your output workspace path to the summary path twice. Try just removing the output workspace from summary. I'm assuming, of course, that you have your other variables, such as output_workspace and stats, defined in a different part of the script.

MeredithGreen
New Contributor III

It worked! Output workspace and stats are defined elsewhere.  So the new script is shown as this instead:

for file in arcpy.ListFiles("*.txt"):

    loss_table = os.path.join(output_workspace, str(file[:-4]))

    summary = (str(loss_table + "summ"))

    arcpy.TableToGeodatabase_conversion(file, output_workspace)

    arcpy.Statistics_analysis(loss_table, summary, stats, "CensusBlock")

Thanks so much for the tip!

SepheFox
Frequent Contributor

You are very welcome. I'm just happy I could actually solve a python problem--a fairly rare event!

0 Kudos
curtvprice
MVP Esteemed Contributor

Meredith, here are few suggested improvements:

1. Use  os.path.splitext() to get the filename without the extension (safer)

2. Use .format() instead of appending strings (easier to read and debug)

3. Use CopyRows instead of TableToGeodatabase (this gives you more control over what the output is named)

for file in arcpy.ListFiles("*.txt"):
    loss_table = os.path.join(output_workspace, os.path.splitext(file)[0])
    summary = "{}summ".format(loss_table)
    arcpy.CopyRows_management(file, loss_table)
    arcpy.Statistics_analysis(loss_table, summary, stats, "CensusBlock")