Open a text file beginning with agr* in python to incorporate in model builder

3401
1
Jump to solution
07-30-2014 10:34 AM
MeredithGreen
New Contributor III

I have an iterator that is going through a folder and iterating through every folder inside of it that begins with a*.  Next I need a script or tool that opens text files located inside the a* folder that begin with agr*.  Then I need to take that agr* text file and plug it into a Table to Table tool.  Does anyone have any idea of the best way to approach this?

0 Kudos
1 Solution

Accepted Solutions
IanMurray
Frequent Contributor

Yes this is very feasible with python.  Using arcpy.da.Walk, we can go through all subdirectories of a selected work space and get all the text files that are within them.  Then we check if they start with "agr" and if we do, add the file path and file name to an empty list, which can iterate over for the table to table tool.

Some sample code to get you going.

import arcpy

import os

#Set your own workspace below

workspace = "c:/data" #Example

text_files = []

for dirpath, dirnames, filenames in arcpy.da.Walk(workspace, datatype="Text"):

  for dirname in dirnames:

    for filename in filenames:

      if (dirname[0] == "a") and (filename[0:2] == "agr"):

        text_files.append(os.path.join(dirpath, filename))

outLoc = "C:/data/Output" #Example

for textfile in text_files:

  outName = textfile.split("\\")[-1]

  arcpy.TableToTable_conversion(textfile, outLoc, outName) #Fill in optional parameters as needed

View solution in original post

1 Reply
IanMurray
Frequent Contributor

Yes this is very feasible with python.  Using arcpy.da.Walk, we can go through all subdirectories of a selected work space and get all the text files that are within them.  Then we check if they start with "agr" and if we do, add the file path and file name to an empty list, which can iterate over for the table to table tool.

Some sample code to get you going.

import arcpy

import os

#Set your own workspace below

workspace = "c:/data" #Example

text_files = []

for dirpath, dirnames, filenames in arcpy.da.Walk(workspace, datatype="Text"):

  for dirname in dirnames:

    for filename in filenames:

      if (dirname[0] == "a") and (filename[0:2] == "agr"):

        text_files.append(os.path.join(dirpath, filename))

outLoc = "C:/data/Output" #Example

for textfile in text_files:

  outName = textfile.split("\\")[-1]

  arcpy.TableToTable_conversion(textfile, outLoc, outName) #Fill in optional parameters as needed