Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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
add comment

2 Answers 2

up vote 7 down vote accepted
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

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
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
1  
It´s working now. Thanks a lot to both of you !! –  Martin Jul 20 '12 at 13:48
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
show 2 more comments

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
add comment

Your Answer

 
discard

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.