[GIS] Using %i%”.csv” in ArcPy to name output CSV file

arcpy

I am using arcpy to describe datasets and output the results into a csv file. I am doing this via a script in arctoolbox and would like to save the file in the same folder as the file being analysed. I don´t want to overwrite any existing files, and thus would like to simply add a number to the file name.

In the FieldCalculator we can use %i% or %n% to have a variable suffix – for example if my output txt file is called output.txt and a second output.txt is created, this is automatically changed to output01.txt

I want to do the same with ModelBuilder but if I can´t use %i%.

import arcpy, os
from arcpy import env
import os.path

env.overwriteOutput = True

#Enter FeatureClass path in modelbuilder dialog
fc = arcpy.GetParameterAsText(0)
ischecked  = arcpy.GetParameterAsText(1)

#Get FeatureClass name
fcname = os.path.basename(fc)

#define Output Directory
outputTxtFilePath = "PATH"

#Define filename
outputTxtFilename = "\\"+fcname+ %i% +".txt"

#full path of file
outputTxtFile = outputTxtFilePath+outputTxtFilename

# Create a list of fields using the ListFields function
fields = arcpy.ListFields(fc)

#open csv file
csv = open(outputTxtFile,'w')

#write describe results to txt file
csv.write(fc)
for field in fields:

    #create string
    txtStr = "Feldname: {0} \n Type: {1} \n Länge {2}".format(field.name, field.type, field.length) + '\n' 

    csv.write(txtStr)

csv.close()

#Open the txt file if is checked
if str(ischecked) == 'true':

    os.system('notepad '+outputTxtFile)

else:
    exit

it works ok if I remove %i%, but then each file gets overwritten.

Best Answer

You could add a python function that pulls any number value from the defined output text file name and adds or assigns 1 to it:

def getValue(x): 
  try:
    return ''.join(i for i in x if i.isdigit()) 
  except ValueError:
    pass

fcname = os.path.basename(fc)
fcnameNoEXT = fcname.split('.')[0]

i = 1
if os.path.exists(fc):
  value = getValue(fcname)
  if value:
    newValue = i + int(value)
    outputTxtFilename = "\\"+fcnameNoEXT.replace(str(value),str(newValue))+ ".txt"
  else:
    outputTxtFilename = "\\"+fcnameNoEXT+ "{}.txt".format(i)
Related Question