I have a Script Tool written that asks the User to specify multiple parameters, one of which is a multi-value file parameter. I want to copy the specified files into the folder being created by the Script Tool.
Here is what I've got:
marketName = "TUC"
siteSpan = "1_SC"
NFID = "1705AZTC_001"
designFiles = arcpy.GetParameterAsText(0) # r"Z:\PROJECTS_2017\VERIZON\PHOENIX_GDB\GIS\919 - CAPITOL\Central Polk SC\919108 - PHO CENTRAL POLK SC_23AUG17.pdf;Z:\PROJECTS_2017\VERIZON\PHOENIX_GDB\GIS\919 - CAPITOL\Central Polk SC\919108 - PHO CENTRAL POLK SC_23AUG17.dwg"
out_FolderPath = r"U:\Development Environment\Geometry"
arcpy.AddMessage(designFiles)
gdb_NewName = marketName + "_" + NFID
out_FolderName = "_" + siteSpan
out_GDBLoc = os.path.join(out_FolderPath, out_FolderName)
dFileStr = designFiles.split(";")
for dFile in dFileStr:
try:
shutil.copy2(dFile, out_GDBLoc)
arcpy.AddMessage("File " + dFile + " copied")
# print "File " + dFile + " copied"
except IOError as E:
arcpy.AddMessage(E)
# print E
The above code is messy. But, it highlights both the Stand-Alone Script and the Script used by the Script Tool. If you replace the arcpy.GetParametersAsText(index) with the commented values and run it as a stand-alone script through IDLE, it will copy the files to specified directory just fine. But, when the files get passed through the arcpy.GetParametersAsText(index) to the script it fails with the following IOError:
Executing: FileCopy 'U:\Development Environment\Geometry\_2_SC\PHO Gateway.pdf';'U:\Development Environment\Geometry\_2_SC\1706AVUH.017 - PHO HONEYWELL - REVISION.pdf'
Start Time: Tue Nov 14 04:57:24 2017
Running script FileCopy...
'U:\Development Environment\Geometry\_2_SC\PHO Gateway.pdf';'U:\Development Environment\Geometry\_2_SC\1706AVUH.017 - PHO HONEYWELL - REVISION.pdf'
[Errno 22] invalid mode ('rb') or filename: u"'U:\\Development Environment\\Geometry\\_2_SC\\PHO Gateway.pdf'"
[Errno 22] invalid mode ('rb') or filename: u"'U:\\Development Environment\\Geometry\\_2_SC\\1706AVUH.017 - PHO HONEYWELL - REVISION.pdf'"
Completed script FileCopy...
Succeeded at Tue Nov 14 04:57:24 2017 (Elapsed Time: 0.04 seconds)
Any input would be deeply appreciated.
So, after the split(";") the resulting literal string which was a file path included a leading and trailing apostrophe. When the shutil.copy2 attempts to run it adds its own u" " to the string and that is not recognized as a file.
The fix was to add a strip() function to remove the leading and trailing apostrophes. The result looks like this:
designFiles = arcpy.GetParameterAsText(0)
dFileStr = designFiles.split(";")
for dFile in dFileStr:
dF = dFile.strip("'")
if os.path.isfile(dF):
try:
arcpy.AddMessage("Is File")
shutil.copy2(dF, out_GDBLoc)
arcpy.AddMessage("File " + dFile + " copied")
# print "File " + dFile + " copied"
except IOError as E:
arcpy.AddMessage(E)
# print E
else:
arcpy.AddMessage("Is Not File")