Access is Denied (os.remove)

3373
7
Jump to solution
08-20-2013 08:57 AM
GeoffOlson
Occasional Contributor
I'm trying to create a DDP export to PDF script that uses the ESRI Example from South Kingstown, RI, and when I run my script I get this error:

Runtime error  Traceback (most recent call last):   File "<string>", line 17, in <module> WindowsError: [Error 5] Access is denied: 'R:\\GIS\\...\\PDF'


I thinks due to this bit of code:
if multiPage == "true":     if os.path.exists(outputPDF):         os.remove(outputPDF)      #Create new FinalMapBook that results will be appeneded into     finalMapBook = arcpy.mapping.PDFDocumentCreate(outputPDF)


I have full access to the drive and the folder.  I tried my local drive and I get the same error.  Any ideas?
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
MattSayler
Occasional Contributor II
When you say the tool won't run (after correcting the path issue), is it that you get the same error, or the tool dialog itself shows an issue (red X)?

If it's the tool dialog, then you might need to adjust how the parameter is set up. If it's set up as a 'file', validation does check if the file exists.

View solution in original post

0 Kudos
7 Replies
MattSayler
Occasional Contributor II
Can you post the whole script please?

Make sure you're passing a file path and not just a directory path too. I think that will cause an error.
0 Kudos
GeoffOlson
Occasional Contributor
I noticed it was just a folder location listed, I set the tool parameter wrong.  But when I do specify a file name, the tool won't run because it says the file doesn't exist.  I don't have the problem when I won't run a multi-page pdf export, but it doesn't create documents either.  I don't know what changed to keep it from the file creation, but it says it completes the script on single page PDFs.

import arcpy, os, sys

#set map doc and the layer to be used
mxd = arcpy.mapping.MapDocument("Current")
mapLyr = arcpy.mapping.ListLayers(mxd, "Detail_2013")[0]



#Get input parameters
pageNumList = arcpy.GetParameterAsText(0).split(";")
multiPage = arcpy.GetParameterAsText(1)
outputPDF = arcpy.GetParameterAsText(2)


if multiPage == "true":
    if os.path.exists(outputPDF):
        os.remove(outputPDF)

    #Create new FinalMapBook that results will be appeneded into
    finalMapBook = arcpy.mapping.PDFDocumentCreate(outputPDF)




#Listing the text elements on the page
concatElem1 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "concat1")[0]
concatElem2 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "concat2")[0]


#Get page number from data driven page - specified in the tool parameter dialogue box
ddp = mxd.dataDrivenPages





for pageNum in pageNumList:
    arcpy.AddMessage(pageNum)
    pageID = mxd.dataDrivenPages.getPageIDFromName(str(pageNum))
    mxd.dataDrivenPages.currentPageID = pageID
    
  
    #Set layer definition query, this contols the rowcount variable
    pageFieldValue = pageNum
    mapLyr.definitionQuery = '"pageNum" = %s' % pageNum
    
    #Finds the number of features in the map and sets up the lists to evenly distribute into the two text elements/columns
    rowcount = int(arcpy.GetCount_management("Detail_2013").getOutput(0))
    percolumn = round(rowcount / 2.0)
    count1 = 1
    count2 = rowcount

    #Specifies the features being used for the SearchCursor
    rows = arcpy.SearchCursor(mapLyr, "", "", "CONCAT")
    fieldrow  = arcpy.SearchCursor(mapLyr, "", "", "pageNum")
    currentpage = ""

    text_var1 = str()
    text_var2 = str()
    
    for row in fieldrow:
        if currentpage != row.pageNum:
            currentpage = row.pageNum
            for row in rows:
                if count1 <= percolumn:
                    text_var1 += '{0}{1}'.format(row.getValue("CONCAT"), os.linesep)
                    concatElem1.text = text_var1
                    count1 += 1
                elif count2 > percolumn:
                    text_var2 += '{0}{1}'.format(row.getValue("CONCAT"), os.linesep)
                    concatElem2.text = text_var2
                    count2 - 1
                else:
                    pass
        else:
            pass

            
      #Generate multi-page PDF file or single PDF files 
    if multiPage == "true": #Appends all PDFs into single, multi-page PDF
        arcpy.mapping.ExportToPDF(mxd, outputPDF[:-4] + pageNum + ".pdf") #strip away .pdf, add platnum value and add ".pdf"
        finalMapBook.appendPages(outputPDF[:-4] + pageNum + ".pdf") #append page to final PDF
        os.remove(outputPDF[:-4] + pageNum + ".pdf")  #no longer needed once appended
    else: #Create individual PDFs for each page
        arcpy.mapping.ExportToPDF(mxd, outputPDF[:-4] + pageNum + ".pdf")

#Add PDF properties for multi-page PDF
if multiPage == "true":
    finalMapBook.updateDocProperties("2010-2011 Crash Report", "2010-2011 Crash Report", "map sheets, map book", "USE_THUMBS")
    finalMapBook.saveAndClose()

arcpy.RefreshActiveView()
arcpy.AddMessage("PROCESS COMPLETED")


#Removed the definition query so all page numbers appear when the script is run next and refresh he layout view
mapLyr.definitionQuery = ""
arcpy.RefreshActiveView()
del mxd, row, rows, rowcount, percolumn, count1, count2
0 Kudos
MattSayler
Occasional Contributor II
When you say the tool won't run (after correcting the path issue), is it that you get the same error, or the tool dialog itself shows an issue (red X)?

If it's the tool dialog, then you might need to adjust how the parameter is set up. If it's set up as a 'file', validation does check if the file exists.
0 Kudos
RhettZufelt
MVP Frequent Contributor
What happens if you hard code your outputPDF?

something like:

outputPDF = r"C:\Project\MapBook.pdf"

and make sure the C:\Project folder exists.

I'm wondering if the path isn't being passed correctly.

R_
0 Kudos
DaveBarrett
Occasional Contributor
Hi,

in addition to rzufelt comment, I have had issues of paths not being passed back correctly to the script. On a couple of occasions I have had the path of the scrip prefixed to the path being passed eg

c:\data\tools\script.py d:\work\output.pdf


I found a few solutions that worked for me.
1. Just re linking the script to the tool - not practical but did work.
2. was using code like this:

scriptPath = os.path.dirname(sys.argv[0])
ccPath = os.path.join(os.path.dirname(scriptPath),"ToolData","NATOCountryCode.xml")


although this was more of an issue with referencing additional files.

3. if the path does not exist then split on white space and try again - this can be very hit and miss though
path = "c:\data\tools\script.py d:\work\output.pdf"
cleanedPath = path.split(" ")[1]


Hope some of this helps

Dave
0 Kudos
GeoffOlson
Occasional Contributor
When you say the tool won't run (after correcting the path issue), is it that you get the same error, or the tool dialog itself shows an issue (red X)?

If it's the tool dialog, then you might need to adjust how the parameter is set up. If it's set up as a 'file', validation does check if the file exists.


In the dialog box I get a red "X", why does the file need to exist beforehand?  Okay, I exported a page so I had a pdf file to replace and it worked just fine.  Does this seem odd?  And I have to browse to the folder and select the file.  For some reason, even though the path and file a specified, it won't go unless I manually choose that file.
0 Kudos
MattSayler
Occasional Contributor II
In the dialog box I get a red "X", why does the file need to exist beforehand?  Okay, I exported a page so I had a pdf file to replace and it worked just fine.  Does this seem odd?  And I have to browse to the folder and select the file.  For some reason, even though the path and file a specified, it won't go unless I manually choose that file.


It's just part of the built in validation. There is an option on the parameter to change the Direction to "Output" instead of "Input". Doesn't look like that requires the file to exist, and if it already does, it will ask if you want to overwrite (which I think just sets the environment variable).
0 Kudos