3

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?

9
import arcpy
import shutil


outbasename=arcpy.GetParameterAsText(0)
#outfilename=r"C:\" + outbasename + ".txt"  # Original with typo
outfilename = "C:\\" + str(outbasename) + ".txt"
shutil.copyfile("C:\\test.txt",outfilename)

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 '12 at 13:28
  • that's what i get for trying to code on a machine without python – mhoran_psprep Jul 20 '12 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. – Michael Markieta Jul 20 '12 at 13:34
  • 3
    \" 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
  • 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). – blord-castillo Jul 20 '12 at 14:23
4

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, privacy policy and cookie policy

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