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: Using ArcGIS ModelBuilder to perform In-line variable substitution for input data path?

2 Answers 2

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

  • Thanks, unfortunately I´m getting an error message: <type 'exceptions.IOError'>: [Errno 22] invalid mode ('wb') or filename: 'C:\\" + outbasename.txt'
    – Martin
    Jul 20, 2012 at 13:28
  • that's what i get for trying to code on a machine without python Jul 20, 2012 at 13:32
  • 1
    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. Jul 20, 2012 at 13:34
  • 3
    \" escapes the second ". You will need to replace the line with this text.... outfilename = "C:\\" + str(outbasename) + ".txt" Jul 20, 2012 at 13:45
  • 2
    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). Jul 20, 2012 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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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