Friday, August 6, 2010

3 Quick Python Tips to Make Geoprocessing Easier


1. Ignoring escape characters
 
When you export a Python script from Model Builder, you have probably noticed that the “\” in the directory paths are modified in two ways, either “/” or “\\”.  This is because “\” is an escape character.  Basically, “\” tells Python to look at the following character and do something special.  For example “\n” tells Python to start a new line.  However, if you are like me, you usually copy and paste a file path and it is a hassle to have to change every occurrence of “\”.  Luckily there is away to tell Python to ignore the “\” in a string as an escape character.  You can do this by placing an “r” directly in front of the string.  So here are three ways to create the same string:
 
r"C:\Program Files\ArcGIS\ArcToolbox\Toolboxes"
"C:/Program Files/ArcGIS/ArcToolbox/Toolboxes"
"C:\\Program Files\\ArcGIS\\ArcToolbox\\Toolboxes"


2. Getting the directory location of the current script

When creating batch scripts that you will reuse frequently for files in various locations, it can be time consuming to modify the file directory before running the script every time.  One method of making this step easier is by placing the script in the same directory as the files you want to process.  To do this, you can have the script use the directory it is located in using the getcwd function.  This function returns the directory that the script is located in.  First import the os module and then call the getcwd function:

import os

directory = os.getcwd()


3. Create a data stamp

When processing file, you may want to create a date stamp on the end of the file name or write the date to a txt file.  Creating a date stamp is fairly easy First import the time module, then call the localtime function to return the current date and time on the system.  This example returns a string in the “MM_DD_YYYY format:

import time

t = time.localtime()

date = str(t[1]) + "_" + str(t[2]) + "_" + str(t[0])



No comments:

Post a Comment