Wednesday, 11 May 2016

arcpy - Calculate Field throws an error when parsing python with backslashes


I have an FTP I need to access through a python script. It works fine with forward slashes, but I don't need it to be read as an html. Below are both sets of code:


Working:


arcpy.CalculateField_management(outShp, "link", '"//ftp/raw" + time.strftime("%Y%m%d") + "/files/boundary" + !NAME! + ".shp"'


Invalid with backslashes:


arcpy.CalculateField_management(outShp, "link", '"\\\\ftp\\raw" + time.strftime(%Y%m%d") + "\\files\\boundary" + !NAME! + ".shp"'

Pretty new, but seems like it should work with the escapes, and does when used in the Calculate Field tool - just doesn't translate to my script.



Answer



I think this should work. Note that I use the r specifier for both the internal and external strings. You can skip the outer one, but then you need to double all backslashes.


arcpy.management.CalculateField("test", "Link", r'r"\\ftp\raw" + time.strftime("%Y%m%d") + r"\files\boundary" + !NAME! + ".shp"', "PYTHON")

Or, slightly longer, but with a more readable string format (less quotes):



arcpy.management.CalculateField("test", "Link", r'r"\\ftp\raw{0:%Y%m%d}\files\boundary{1}.shp".format(datetime.datetime.now(), !NAME!)', "PYTHON")

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...