Saturday, 11 June 2016

arcgis 10.1 - Using ArcPy to verify paths of Hyperlinks?


I've recently come across an issue where some of our hyperlinks aren't working. I'm familiar with python and have made similar scripts before, but I would first like to ask for your assistance to maybe something already pre-existing or another tool to use.


I would like to cycle through all the hyperlink paths for a certain shapefile and search the C:\Scans\ for the path. If the path doesn't exist than I want the path to be written to an excel file.


Can anyone help me with this?


Final code so far


import arcpy
import os

fc = r"G:\GIS\Lauren\Shapes\watermains.shp"

fields = ["Truck_Path"]

with arcpy.da.SearchCursor (fc,fields) as cursor:
for row in cursor:
Roll = str(row[0])
if os.path.exists(Roll):
pass
else:
f = open(r"C:\Scans\BrokenLinks.txt","a")
f.write(Roll + os.linesep)

f.close()

Answer



I made just a couple of modifications to your script.




  1. I fixed your fields variable so that it would not throw an error. Previously, you did not have it wrapped as a string, enclosing with single quotes fixes that problem. This also allows you to expand the script to include additional fields if need be, with a minimum of fuss. It also lets you get rid of the additional variable you had to enter the field name for "Truck_Path".




  2. Where you are testing to see if the string exists, I changed the reference there to be the variable Roll, which is what you assigned the file path attribute to. This way, it is searching to see if the file path in that variable exists, as opposed to Truck_Path which is what you had before, which would have simply searched for the text, "Truck_Path".





  3. I added simple code to open an existing text file, write the file path into it if there was no match, and close it again. This file would be easy enough to open in Excel for further modification, but doesn't require bringing in a specific module for handling Excel.




  4. Removing a number of the Import references that you have. Unless you plan to use them later, no sense referencing them because I think Python tries to verify them whether they are used or not, thus causing slight overhead on the script. I'm not completely sure about that, but the simpler the better.




Here is the updated code:


import arcpy
import os


fc = r"G:\GIS\water\watermains.shp"
fields = '["Truck_Path"]'

with arcpy.da.SearchCursor (fc,fields) as cursor:
for row in cursor:
Roll = str(row[0])
if os.path.exists(Roll):
pass
else:

logfile = open(r"c:\filepath.txt","a")
logtext = Roll + os.linesep
logfile.write(logtext)
logfile.close()

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...