Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I´m trying to use a variable as part of the output path of a shutil command. Unfortunately I couldn´t work it out how to do it. Can anybody help?

import arcpy
import shutil
Name = arcpy.GetParameterAsText(0)
shutil.copyfile("C:\\test.txt", "C:\\%Name%.txt")

This question here is similar, but was never answered: ArcGIS 10 Model Builder In-line variable substitution for input data path

share|improve this question
up vote 9 down vote accepted
import arcpy
import shutil

#outfilename=r"C:\" + outbasename + ".txt"  # Original with typo
outfilename = "C:\\" + str(outbasename) + ".txt"

this is how I would do it in arcpy in a script tool

share|improve this answer
Thanks, unfortunately I´m getting an error message: <type 'exceptions.IOError'>: [Errno 22] invalid mode ('wb') or filename: 'C:\\" + outbasename.txt' – Martin Jul 20 '12 at 13:28
You may not have permission to write to that location. IOError usually occur when Python has trouble completing a task that requires writing to the disk. – Michael Markieta Jul 20 '12 at 13:34
\" escapes the second ". You will need to replace the line with this text.... outfilename = "C:\\" + str(outbasename) + ".txt" – Michael Markieta Jul 20 '12 at 13:45
It´s working now. Thanks a lot to both of you !! – Martin Jul 20 '12 at 13:48
An alternative is to use string substitution. outfilename="C:\\%s.txt" % (outbasename) The %s means that a string is substituted at that location from the tuple that follows (in this case containing only the variable outbasename, which will be coerced to a string). – blord-castillo Jul 20 '12 at 14:23

Have a look at the os.path namespace for common pathname manipulations. I would also parameterize the input file and output locations instead of hardcoding them but of course that's up to you.

I would do something like this:

import arcpy, os, shutil
inputfile = arcpy.GetParameterAsText(0)
ext = os.path.splitext(inputfile)[1] # returns file extension, e.g. ".txt"
outbasename = arcpy.GetParameterAsText(1)
outfolder = arcpy.GetParameterAsText(2)
outfilename = os.path.join(outfolder, outbasename + ext)
shutil.copyfile(inputfile, outfilename)
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.