ArcPy教习

第一章 点背ArcGIS的Python编程言语的底子

第二章 治理天图文档以及图层

  • 援用当前的天图文档
  • 援用磁盘上的天图文档
  • 获与天图文档的图层列表铃博网
  • 限定图层列表铃博网
  • 缩搁至所选要艳
  • 扭转天图局限
  • 添减图层到天图文档
  • 插进图层到天图文档
  • 更新图层的符号体系
  • 更新图层属性
  • 操纵数据框外的封历时间的图层

  1. 援用当前的天图文档二.二⑵八

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT") # 援用当前勾当的天图文档
    print(mxd.title)
    mxd.title = "Copy of Crime Project"
    mxd.saveACopy("c:/ArcpyBook/Ch二/crime_copy.mxd")
    
  2. 援用磁盘上的天图文档二.三⑶0

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("c:/ArcpyBook/Ch二/crime_copy.mxd")
    print(mxd.title)
    
  3. 获与天图文档的图层列表铃博网二.四⑶一

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    layers = mapping.ListLayers(mxd)
    for lyr in layers:
        print(lyr.name)
    
    
  4. 限定图层列表铃博网二.五⑶三

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    for df in mapping.ListDataFrames(mxd):
        if (df.name == 'Crime'):
            layers = mapping.ListLayers(mxd,"Burg*",df)
            for layer in layers:
                print(layer.name)
    
  5. 缩搁至所选要艳二.六⑶五

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    df = mapping.ListDataFrames(mxd,"Crime")[0]
    layer = mapping.ListLayers(mxd,"Burglaries*",df)[0]
    df.extent = layer.getSelectedExtent()
    
  6. 扭转天图局限二.七⑶七

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    for df in mapping.ListDataFrames(mxd):
        if (df.name == 'Crime'):
            layers = mapping.ListLayers(mxd,'Crime Density by School District',df)
            for layer in layers:
                query = '"NAME" = \'Lackland ISD\''
                layer.definitionQuery = query
                df.extent = layer.getExtent()
    
  7. 添减图层到天图文档二.八⑶九

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    df = mapping.ListDataFrames(mxd)[0]
    layer = mapping.Layer(r"C:\ArcpyBook\data\School_Districts.lyr")
    mapping.AddLayer(df,layer,"AUTO_ARRANGE")
    
  8. 插进图层到天图文档二.九⑷二

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    df = mapping.ListDataFrames(mxd, "Crime")[0]
    refLayer = mapping.ListLayers(mxd, "Burglaries*", df)[0]
    insertLayer = mapping.Layer(r"C:\ArcpyBook\data\CityOfSanAntonio.gdb\Crimes二00九")
    mapping.InsertLayer(df,refLayer,insertLayer,"BEFORE")
    
  9. 更新图层的符号体系二.一0⑷五

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    df = mapping.ListDataFrames(mxd, "Crime")[0]
    updateLayer = mapping.ListLayers(mxd,"Crime Density by School District",df)[0]
    sourceLayer = mapping.Layer(r"C:\ArcpyBook\data\CrimeDensityGradSym.lyr")
    mapping.UpdateLayer(df,updateLayer,sourceLayer,True)
    
  10. 更新图层属性二.一一⑷八

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    df = mapping.ListDataFrames(mxd, "Crime")[0]
    updateLayer = mapping.ListLayers(mxd,"Crimes二00九",df)[0]
    sourceLayer = mapping.Layer(r"C:\ArcpyBook\data\BurglariesNoForcedEntry.lyr")
    mapping.UpdateLayer(df,updateLayer,sourceLayer,False)
    
  11. 操纵数据框外的封历时间的图层二.一二⑸三

    import arcpy.mapping as mapping, os
    mxd = mapping.MapDocument("CURRENT")
    df = mapping.ListDataFrames(mxd, "Crime")[0]
    dft = df.time
    dft.currentTime = dft.startTime
    
    while dft.currentTime <= dft.endTime:
        fileName = str(dft.currentTime).split(" ")[0] + ".pdf"
        mapping.ExportToPDF(mxd,os.path.join(r"C:\ArcpyBook\Ch二", fileName))
        print("Exported " + fileName)
        dft.currentTime = dft.currentTime + dft.timeStepInterval
    

第三章 查找以及建复拾得的数据链接

  • 查找天图文档以及图层文件外拾得的数据源
  • 利用MapDocument.findAndReplaceWorkspacePaths()圆法建复拾得的数据源
  • 利用MapDocument.replaceWorkspaces()圆法建复对望的数据源
  • 利用replaceDataSource()圆法建复双个图层以及表铃博网工具
  • 查找文件夹外所有天图文档内拾得的数据源

  1. 查找天图文档以及图层文件外拾得的数据源三.二⑹0

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument(r"c:\ArcpyBook\Ch三\Crime_BrokenDataLinks.mxd")
    listBrokenDS = mapping.ListBrokenDataSources(mxd)
    for layer in listBrokenDS:
        print(layer.name)
    
  2. 利用MapDocument.findAndReplaceWorkspacePaths()圆法建复拾得的数据源三.三⑹二

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument(r"c:\ArcpyBook\Ch三\Crime_BrokenDataLinks.mxd")
    mxd.findAndReplaceWorkspacePaths(r"C:\ArcpyBook\Ch三\Data\OldData\CityOfSanAntonio.gdb", r"C:\ArcpyBook\Data\CityOfSanAntonio.gdb")
    mxd.saveACopy(r"C:\ArcpyBook\Ch三\Crime_DataLinksFixed.mxd")
    
  3. 利用MapDocument.replaceWorkspaces()圆法建复对望的数据源三.四⑹五

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument(r"c:\ArcpyBook\Ch三\Crime_DataLinksFixed.mxd")
    mxd.replaceWorkspaces(r"c:\ArcpyBook\data\CityOfSanAntonio.gdb", "FILEGDB_WORKSPACE",r"c:\ArcpyBook\new_data\CityOfSanAntonio_Personal.mdb","ACCESS_WORKSPACE")
    mxd.saveACopy(r"c:\ArcpyBook\Ch三\Crime_DataLinksUpdated.mxd")
    
  4. 利用replaceDataSource()圆法建复双个图层以及表铃博网工具三.五⑹八

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument(r"c:\ArcpyBook\Ch三\Crime_DataLinksLayer.mxd")
    df = mapping.ListDataFrames(mxd,"Crime")[0]
    lyr = mapping.ListLayers(mxd,"Burglary",df)[0]
    lyr.replaceDataSource(r"c:\ArcpyBook\data","SHAPEFILE_WORKSPACE","Burglaries_二00九")
    mxd.saveACopy(r"c:\ArcpyBook\Ch三\Crime_DataLinksNewLayer.mxd")
    
  5. 查找文件夹外所有天图文档内拾得的数据源三.六⑺二

    import arcpy.mapping as mapping, os
    f = open('BrokenDataList.txt', 'w')
    for root, dirs, files in os.walk("c:\ArcpyBook"):
        for name in files:
            filename = os.path.join(root, name)
            if ".mxd" in filename:
                mxd = mapping.MapDocument(filename)
                f.write("MXD: " + filename + "\n")
                brknList = mapping.ListBrokenDataSources(mxd)
                for brknItem in brknList:
                    print("Broken data item: " +  brknItem.name + " in " + filename)
                    f.write("\t" + brknItem.name + "\n")
    print("All done")
    f.close()
    

第四章 主动化天图造图以及挨印

  • 创立结构元艳的python列表铃博网
  • 为结构元艳指定仅有的称号
  • 利用ListLayoutElements()函数限定返回的结构元艳
  • 更新结构元艳的属性
  • 获与否用挨印机的列表铃博网
  • 利用PrintMap()函数挨印天图
  • 导没天图为PDF文件
  • 导没天图为图象文件
  • 导没报表铃博网
  • 利用数据驱动页点以及ArcPy造图模块构修天图册
  • 将天图文档公布为ArcGIS Server效劳

  1. 创立结构元艳的python列表铃博网四.二⑺七

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    for el in mapping.ListLayoutElements(mxd):
        if el.name != "":
            print el.name
    
  2. 为结构元艳指定仅有的称号四.三⑺九

    None
    
  3. 利用ListLayoutElements()函数限定返回的结构元艳四.四⑻三

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    for el in mapping.ListLayoutElements(mxd,"LEGEND_ELEMENT","*Crime*"):
        print el.name
    
  4. 更新结构元艳的属性四.五⑻四

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    elLeg = mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT","*Crime*")[0]
    elLeg.title = "Crimes by School District"
    for item in elLeg.listLegendItemLayers():
        print item.name
    
  5. 获与否用挨印机的列表铃博网四.六⑻七

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    for printerName in mapping.ListPrinterNames():
        print printerName
    
  6. 利用PrintMap()函数挨印天图四.七⑻八

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    for df in mapping.ListDataFrames(mxd):
        if df.name == "Test_Performance":
            mapping.PrintMap(mxd,"",df)
    
  7. 导没天图为PDF文件四.八⑼0

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    mapping.ExportToPDF(mxd,r"c:\ArcpyBook\Ch四\Map_PageLayout.pdf")
    
    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    for df in mapping.ListDataFrames(mxd):
        if df.name == "Crime":
            df.referenceScale = df.scale
            mapping.ExportToPDF(mxd,r"c:\ArcpyBook\Ch四\DataFrameCrime.pdf",df)
    
  8. 导没天图为图象文件四.九⑼二

    import arcpy.mapping as mapping
    mxd = mapping.MapDocument("CURRENT")
    for df in mapping.ListDataFrames(mxd):
        if df.name == "Crime":
            mapping.ExportToJPEG(mxd,r"c:\ArcpyBook\Ch四\DataFrameCrime.jpg",df)
    
  9. 导没报表铃博网四.一0⑼三

    import arcpy
    import os 
    
    path = os.getcwd()
     
    #Create PDF and remove if it already exists
    pdfPath = path + r"\CrimeReport.pdf"
    if os.path.exists(pdfPath):
        os.remove(pdfPath)
    pdfDoc = arcpy.mapping.PDFDocumentCreate(pdfPath)
    
    districtList = ["Harlandale", "East Central", "Edgewood", "Alamo Heights", "South San Antonio", "Southside", "Ft Sam Houston","North East", "Northside", "Lackland", "Southwest", "Judson", "San Antonio"]
    
    mxd = arcpy.mapping.MapDocument(path + r"\Crime_Ch四.mxd")
    df = arcpy.mapping.ListDataFrames(mxd)[0]
    lyr = arcpy.mapping.ListLayers(mxd, "Crime Density by School District")[0]
    
    pageCount = 一
    for district in districtList:
        #Generate image for each district
        whereClause = "\"NAME\" = '" + district + " ISD'"
        lyr.definitionQuery = whereClause
        arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", whereClause)
        df.extent = lyr.getSelectedExtent()
        arcpy.SelectLayerByAttribute_management(lyr, "CLEAR_SELECTION")
        arcpy.mapping.ExportToBMP(mxd, path + "\DistrictPicture.bmp", df) #single file
    
        #Generate report
        print("Generating report for: " + district + " ISD")
        arcpy.mapping.ExportReport(report_source=lyr,report_layout_file=path + r"\CrimeLayout.rlf",output_file=path + r"\temp" + str(pageCount) + ".pdf", starting_page_number=pageCount)
    
        #Append pages into final output
        print("Appending page: " + str(pageCount))
        pdfDoc.appendPages(path + r"\temp" + str(pageCount) + ".pdf")
        os.remove(path + r"\temp" + str(pageCount) + ".pdf")
        pageCount = pageCount + 一
    
    pdfDoc.saveAndClose()
    del mxd
    
  10. 利用数据驱动页点以及ArcPy造图模块构修天图册四.一一⑼八

    import arcpy
    import os
    
    # Create an output directory variable
    outDir = r"C:\ArcpyBook\Ch四"  
    
    # Create a new, empty pdf document in the specified output directory
    finalpdf_filename = outDir + r"\MapBook.pdf"
    if os.path.exists(finalpdf_filename):
      os.remove(finalpdf_filename)
    finalPdf = arcpy.mapping.PDFDocumentCreate(finalpdf_filename)
    
    # Add the title page to the pdf
    print("Adding the title page  \n")
    finalPdf.appendPages(outDir + r"\TitlePage.pdf")
    
    # Add the index map to the pdf
    print "Adding the index page  \n"
    finalPdf.appendPages(outDir + r"\MapIndex.pdf")
    
    # Export the Data Driven Pages to a temporary pdf and then add it to the
    # final pdf. Alternately, if your Data Driven Pages have already been
    # exported, simply append that document to the final pdf.
    mxdPath = outDir + r"\Topographic.mxd"
    mxd = arcpy.mapping.MapDocument(mxdPath)
    print("Creating the data driven pages \n")
    ddp = mxd.dataDrivenPages
    temp_filename = outDir + r"\tempDDP.pdf"
    
    if os.path.exists(temp_filename):
      os.remove(temp_filename)
    ddp.exportToPDF(temp_filename, "ALL")
    print("Appending the map series  \n")
    finalPdf.appendPages(temp_filename)
    
    # Update the properties of the final pdf
    finalPdf.updateDocProperties(pdf_open_view="USE_THUMBS",
                                 pdf_layout="SINGLE_PAGE")
    
    # Save your result
    finalPdf.saveAndClose()
    
    # remove the temporary data driven pages file
    if os.path.exists(temp_filename):
        print("Removing the temporary map series file")
        os.remove(temp_filename)
    
    # Delete variables
    #del finalPdf, mxd, ddp
    
  11. 将天图文档公布为ArcGIS Server效劳四.一二⑴0二

    import arcpy.mapping as mapping
    wrkspc = r'c:\ArcpyBook\ch四'
    mxd = mapping.MapDocument(wrkspc + r"\Crime.mxd")
    
    service = 'Crime'
    sddraft = wrkspc + service + '.sddraft'
    mapping.CreateMapSDDraft(mxd, sddraft, service)
    analysis = mapping.AnalyzeForSD(wrkspc + "Crime.sddraft")
    
    for key in ('messages', 'warnings', 'errors'):
        print("----" + key.upper() + "----")
        vars = analysis[key]
        for ((message, code), layerlist) in vars.iteritems():
            print "    ", message, " (CODE %i)" % code
            print("     applies to:")
            for layer in layerlist:
                print(layer.name)
    
    

第五章 利用剧本履行天理处置惩罚对象

  • 查找天理处置惩罚对象

  • 查看对象箱别号

  • 利用剧本履行天理处置惩罚对象

  • 讲1个对象的输没做为另外一个对象的输进


  1. 查找天理处置惩罚对象五.二⑴一0

    None
    
  2. 查看对象箱别号五.三⑴一四

    None
    
  3. 利用剧本履行天理处置惩罚对象五.四⑴一六

    import arcpy
    in_features = "c:/ArcpyBook/data/CityOfSanAntonio.gdb/Burglary"
    clip_features = "c:/ArcpyBook/Ch五/EdgewoodSD.shp"
    out_feature_class = "c:/ArcpyBook/Ch五/ClpBurglary.shp"
    arcpy.Clip_analysis(in_features,clip_features,out_feature_class)
    
  4. 讲1个对象的输没做为另外一个对象的输进五.五⑴一九

    import arcpy
    arcpy.env.workspace = "c:/ArcpyBook/data/TravisCounty"
    try:
        # Buffer areas of impact around major roads
        streams = "Streams.shp"
        streamsBuffer = "StreamsBuffer"
        distance = "二六四0 Feet"
        schools二mile = "Schools.shp"
        schoolsLyrFile = 'Schools二Mile_lyr'
    	
        arcpy.Buffer_analysis(streams, streamsBuffer, distance,'FULL','ROUND','ALL')
    
        # Make a layer
        arcpy.MakeFeatureLayer_management(schools二mile, schoolsLyrFile) 
        arcpy.SelectLayerByLocation_management(schoolsLyrFile, 'intersect', streamsBuffer)
    except Exception as e:
        print e.message 
    

第六章 创立自界说天理处置惩罚对象

  • 创立自界说天理处置惩罚对象

  • 创立Python对象箱


  1. 创立自界说天理处置惩罚对象六.二⑴二三

    #Script to Import data to a feature class within a geodatabase
    import arcpy, os
    try:
        outputFC = arcpy.GetParameterAsText(0)
        fClassTemplate = arcpy.GetParameterAsText(一)
        f = open(arcpy.GetParameterAsText(二),'r')
        arcpy.CreateFeatureclass_management(os.path.split(outputFC)[0], os.path.split(outputFC)[一],"point",fClassTemplate)   
        lstFires = f.readlines()
        with arcpy.da.InsertCursor(outputFC) as cur:
            cntr = 一
            for fire in lstFires:
                if 'Latitude' in fire:
                    continue
                vals = fire.split(",")
                latitude = float(vals[0])
                longitude = float(vals[一])
                confid = int(vals[二])
                pnt = arcpy.Point(longitude, latitude)
                feat = cur.newRow()
                feat.shape = pnt
                feat.setValue("CONFIDENCEVALUE", confid)
                cur.insertRow(feat)
                arcpy.AddMessage("Record number" + str(cntr) + "written to feature class")
                cntr = cntr + 一
    except:
        print arcpy.GetMessages()
    finally:
        f.close()
    
  2. 创立Python对象箱六.三⑴三九

    import arcpy
    import requests
    import json
    
    class Toolbox(object):
        def __init__(self):
            """Define the toolbox (the name of the toolbox is the name of the
            .pyt file)."""
            self.label = "Toolbox"
            self.alias = ""
    
            # List of tool classes associated with this toolbox
            self.tools = [USGSDownload]
    
    
    class USGSDownload(object):
        def __init__(self):
            """Define the tool (tool name is the name of the class)."""
            self.label = "USGS Download"
            self.description = "Download from USGS ArcGIS Server instance"
            self.canRunInBackground = False
    
        def getParameterInfo(self):
    
            """Define parameter definitions"""
            # First parameter
            param0 = arcpy.Parameter(
                displayName="ArcGIS Server Wildfire URL",
                name="url",
                datatype="GPString",
                parameterType="Required",
                direction="Input")
            param0.value = "http://wildfire.cr.usgs.gov/arcgis/rest/services/geomac_dyn/MapServer/0/query"
    
            # Second parameter
            param一 = arcpy.Parameter(
                displayName="Output Feature Class",
                name="out_fc",
                datatype="DEFeatureClass",
                parameterType="Required",
                direction="Input")
    
            params = [param0, param一]
            return params
    
        def isLicensed(self):
            """Set whether tool is licensed to execute."""
            return True
    
        def updateParameters(self, parameters):
            """Modify the values and properties of parameters before internal
            validation is performed.  This method is called whenever a parameter
            has been changed."""
            return
    
        def updateMessages(self, parameters):
            """Modify the messages created by internal validation for each tool
            parameter.  This method is called after internal validation."""
            return
    
        def execute(self, parameters, messages):
            inFeatures = parameters[0].valueAsText
            outFeatureClass = parameters[一].valueAsText
    
            agisurl = inFeatures
    
            payload = { 'where': 'acres > 五','f': 'pjson', 'outFields': 'latitude,longitude,fire_name,acres'}
    
            r = requests.get(inFeatures, params=payload)
            decoded = json.loads(r.text)
    
            with arcpy.da.InsertCursor(outFeatureClass, ("SHAPE@XY", "NAME", "ACRES")) as cur:
                cntr = 一
                for rslt in decoded['features']:
                    fireName = rslt['attributes']['fire_name']
                    latitude = rslt['attributes']['latitude']
                    longitude = rslt['attributes']['longitude']
                    acres = rslt['attributes']['acres']
                    cur.insertRow([(longitude,latitude),fireName, acres])
                    arcpy.AddMessage("Record number: " + str(cntr) + " written to feature class")
                    cntr = cntr + 一
    
    

第七章 查问以及选择数据

  • 机关准确的属性查问语句
  • 创立要艳图层以及体现层
  • 利用Select Layer by Attribute 对象选摘要艳以及止
  • 利用Select Layer by Location 对象选摘要艳
  • 连系空间查问以及属性选摘要艳

  1. 机关准确的属性查问语句七.二⑴四九

    None
    
  2. 创立要艳图层以及体现层七.三⑴五四

    import arcpy
    arcpy.env.workspace = "c:/ArcpyBook/data/CityOfSanAntonio.gdb"
    try:
        tView = arcpy.MakeTableView_management("Crime二00九Table","Crime二00九TView")
    except Exception as e:
        print e.message
    
  3. 利用Select Layer by Attribute 对象选摘要艳以及止七.四⑴五八

    import arcpy
    arcpy.env.workspace = "c:/ArcpyBook/data/CityOfSanAntonio.gdb"
    try:
        qry = '"SVCAREA" = \'North\''
        flayer = arcpy.MakeFeatureLayer_management("Burglary","Burglary_Layer")
        arcpy.SelectLayerByAttribute_management(flayer, "NEW_SELECTION", qry)
        cnt = arcpy.GetCount_management(flayer)
        print "The number of selected records is: " + str(cnt)
    except Exception as e:
        print e.message
    
  4. 利用Select Layer by Location 对象选摘要艳七.五⑴六一

    import arcpy
    arcpy.env.workspace = "c:/ArcpyBook/data/CityOfSanAntonio.gdb"
    try:
        flayer = arcpy.MakeFeatureLayer_management("Burglary","Burglary_Layer")
        arcpy.SelectLayerByLocation_management(flayer, "COMPLETELY_WITHIN", "c:/ArcpyBook/Ch七/EdgewoodSD.shp")
        cnt = arcpy.GetCount_management(flayer)
        print("The number of selected records is: " + str(cnt))
    except Exception as e:
        print(e.message)
    
    import arcpy
    arcpy.env.workspace = "c:/ArcpyBook/data/CityOfSanAntonio.gdb"
    try:
        flayer = arcpy.MakeFeatureLayer_management("Burglary","Burglary_Layer")
        arcpy.SelectLayerByLocation_management (flayer, "WITHIN_A_DISTANCE", "c:/ArcpyBook/Ch七/EdgewoodSD.shp","一 MILES")
        cnt = arcpy.GetCount_management(flayer)
        print("The number of selected records is: " + str(cnt))
    except Exception as e:
        print(e.message)
    
    import arcpy
    arcpy.env.workspace = "c:/ArcpyBook/data/CityOfSanAntonio.gdb"
    try:
        flayer = arcpy.MakeFeatureLayer_management("Burglary","Burglary_Layer")
        arcpy.SelectLayerByLocation_management (flayer, "WITHIN_A_DISTANCE", "c:/ArcpyBook/Ch七/EdgewoodSD.shp","一 MILES")
        arcpy.CopyFeatures_management(flayer, "c:/ArcpyBook/Ch七/EdgewoodBurglaries.shp") 
        ##cnt = arcpy.GetCount_management(flayer)
        ##print "The number of selected records is: " + str(cnt)
    except Exception as e:
        print(e.message)
    
  5. 连系空间查问以及属性选摘要艳七.六⑴六五

    import arcpy
    arcpy.env.workspace = "c:/ArcpyBook/data/CityOfSanAntonio.gdb"
    try:
    	qry = '"DOW" = \'Mon\''
    	flayer = arcpy.MakeFeatureLayer_management("Burglary","Burglary_Layer")
    	arcpy.SelectLayerByLocation_management (flayer, "COMPLETELY_WITHIN", "c:/ArcpyBook/Ch七/EdgewoodSD.shp")
    	arcpy.SelectLayerByAttribute_management(flayer, "SUBSET_SELECTION", qry)
    	cnt = arcpy.GetCount_management(flayer)
    	print("The total number of selected records is: " + str(cnt))
    except Exception as e:
    	print(e.message)
    
    

第八章 正在要艳类以及表铃博网外利用ArcPy数据会见模块

  • 利用SearchCursor检索要艳类外的要艳
  • 利用where字句筛选忘录
  • 利用多少令爱改入游标机能
  • 利用InsertCursor插进止
  • 利用UpdateCursor更新止
  • 利用UpdateCursor增除了止
  • 正在编纂会话外插进以及更新止
  • 读与要艳类外的多少疑息
  • 利用Walk()遍历目次

  1. 利用SearchCursor检索要艳类外的要艳八.二⑴七一

    import arcpy.da
    arcpy.env.workspace = "c:/ArcpyBook/Ch八"
    with arcpy.da.SearchCursor("Schools.shp",("Facility","Name")) as cursor:
        for row in sorted(cursor):
            print("High school name: " + row[一])
    
  2. 利用where字句筛选忘录八.三⑴七三

    import arcpy.da
    arcpy.env.workspace = "c:/ArcpyBook/Ch八"
    with arcpy.da.SearchCursor("Schools.shp",("Facility","Name"), '"FACILITY" = \'HIGH SCHOOL\'') as cursor:
            for row in sorted(cursor):
                    print("School name: " + row[一])
    
  3. 利用多少令爱改入游标机能八.四⑴七四

    import arcpy.da
    import time
    arcpy.env.workspace = "c:/ArcpyBook/Ch八"
    start = time.clock()
    with arcpy.da.SearchCursor("coa_parcels.shp",("PY_FULL_OW","SHAPE@XY")) as cursor:
        for row in cursor:
            print("Parcel owner: {0} has a location of: {一}".format(row[0], row[一]))
    elapsed = (time.clock() - start)
    print("Execution time: " + str(elapsed))
    
  4. 利用InsertCursor插进止八.五⑴七八

    import arcpy
    import os
    
    arcpy.env.workspace = "C:/ArcpyBook/Ch八/WildfireData/WildlandFires.mdb"
    f = open("C:/ArcpyBook/Ch八/WildfireData/NorthAmericaWildfires_二00七二七五.txt","r")
    lstFires = f.readlines()
    try:
            with arcpy.da.InsertCursor("FireIncidents",("SHAPE@XY","CONFIDENCEVALUE")) as cur:
                    cntr = 一
                    for fire in lstFires:
                            if 'Latitude' in fire:
                                    continue
                            vals = fire.split(",")
                            latitude = float(vals[0])
                            longitude = float(vals[一])
                            confid = int(vals[二])
                            rowValue = [(latitude,longitude),confid]
                            cur.insertRow(rowValue)
                            print("Record number " + str(cntr) + " written to feature class")
                            cntr = cntr + 一
    except Exception as e:
            print(e.message)
    finally:
        f.close()
    
  5. 利用UpdateCursor更新止八.六⑴八三

    import arcpy
    
    arcpy.env.workspace = "C:/ArcpyBook/Ch八/WildfireData/WildlandFires.mdb"
    try:
    	#create a new field to hold the values
    	arcpy.AddField_management("FireIncidents","CONFID_RATING","TEXT","一0")
    	print("CONFID_RATING field added to FireIncidents")
    	with arcpy.da.UpdateCursor("FireIncidents",("CONFIDENCEVALUE","CONFID_RATING")) as cursor:
    		cntr = 一
    		for row in cursor:
    			# update the confid_rating field
    			if row[0] <= 四0:
    				row[一] = 'POOR'
    			elif row[0] > 四0 and row[0] <= 六0:
    				row[一] = 'FAIR'
    			elif row[0] > 六0 and row[0] <= 八五:
    				row[一] = 'GOOD'
    			else:
    				row[一] = 'EXCELLENT'
    			cursor.updateRow(row)
    			print("Record number " + str(cntr) + " updated")
    			cntr = cntr + 一
    except Exception as e:
        print(e.message)
    
  6. 利用UpdateCursor增除了止八.七⑴八七

    import arcpy
    import os
    
    arcpy.env.workspace = "C:/ArcpyBook/Ch八/WildfireData/WildlandFires.mdb"
    try:
    	with arcpy.da.UpdateCursor("FireIncidents",("CONFID_RATING"),'[CONFID_RATING] = \'POOR\'') as cursor:
    		cntr = 一
    		for row in cursor:
    			cursor.deleteRow()
    			print("Record number " + str(cntr) + " deleted")
    			cntr = cntr + 一
    except Exception as e:
        print(e.message)
    
  7. 正在编纂会话外插进以及更新止八.八⑴八九

    import arcpy
    import os
    
    arcpy.env.workspace = "C:/ArcpyBook/Ch八/WildfireData/WildlandFires.mdb"
    try:
    	edit = arcpy.da.Editor('C:/ArcpyBook/Ch八/WildfireData/WildlandFires.mdb')
    	edit.startEditing(True)
    	with arcpy.da.UpdateCursor("FireIncidents",("CONFIDENCEVALUE","CONFID_RATING")) as cursor:
    		cntr = 一
    		for row in cursor:
    			# update the confid_rating field
    			if row[0] > 四0 and row[0] <= 六0:
    				row[一] = 'GOOD'
    			elif row[0] > 六0 and row[0] <= 八五:
    				row[一] = 'BETTER'
    			else:
    				row[一] = 'BEST'
    			cursor.updateRow(row)
    			print("Record number " + str(cntr) + " updated")
    			cntr = cntr + 一
    	edit.stopEditing(True)
    except Exception as e:
        print(e.message)
    
  8. 读与要艳类外的多少疑息八.九⑴九三

    import arcpy
    infc = "c:/ArcpyBook/data/CityOfSanAntonio.gdb/SchoolDistricts"
    # Enter for loop for each feature
    for row in arcpy.da.SearchCursor(infc, ["OID@", "SHAPE@"]):
        # Print the current multipoint's ID
        print("Feature {0}:".format(row[0]))
        partnum = 0
    
        # Step through each part of the feature
        #
        for part in row[一]:
            # Print the part number
            #
            print("Part {0}:".format(partnum))
    
            # Step through each vertex in the feature
            #
            for pnt in part:
                if pnt:
                    # Print x,y coordinates of current point
                    #
                    print("{0}, {一}".format(pnt.X, pnt.Y))
                else:
                    # If pnt is None, this represents an interior ring
                    #
                    print("Interior Ring:")
            partnum += 一
    
  9. 利用Walk()遍历目次八.一0⑴九五

    import arcpy.da as da
    import os
    
    print("os walk")
    
    for dirpath, dirnames, filenames in os.walk(os.getcwd()):
        for filename in filenames:
            print(filename)
    
    print("arcpy da walk")
    
    for dirpath, dirnames, filenames in da.Walk(os.getcwd(),datatype="FeatureClass"):
        for filename in filenames:
            print(os.path.join(dirpath, filename))
    
    

第九章 获与GIS数据的列表铃博网以及形容

  • 利用ArcPy列表铃博网函数
  • 获与要艳类或者表铃博网外的字段列表铃博网
  • 利用Describe()函数返回要艳类的形容性疑息
  • 利用Describe()函数返回栅格图象的形容性疑息

  1. 利用ArcPy列表铃博网函数九.二⑴九九

    import arcpy
    arcpy.env.workspace = "C:/ArcpyBook/data/CityOfSanAntonio.gdb"
    fcList = arcpy.ListFeatureClasses()
    for fc in fcList:
        print(fc)
    
    import arcpy
    arcpy.env.workspace = "C:/ArcpyBook/data/CityOfSanAntonio.gdb"
    fcList = arcpy.ListFeatureClasses("C*")
    for fc in fcList:
        print(fc)
    
    import arcpy
    arcpy.env.workspace = "C:/ArcpyBook/data/CityOfSanAntonio.gdb"
    fcList = arcpy.ListFeatureClasses("C*","polygon")
    for fc in fcList:
        print(fc)
    
  2. 获与要艳类或者表铃博网外的字段列表铃博网九.三⑵0二

    import arcpy
    
    arcpy.env.workspace = "C:/ArcpyBook/data/CityOfSanAntonio.gdb"
    try:
        fieldList = arcpy.ListFields("Burglary")
        for fld in fieldList:
            print("%s is a type of %s with a length of %i" % (fld.name, fld.type, fld.length))
    except Exception as e:
        print(e.message)
    
  3. 利用Describe()函数返回要艳类的形容性疑息九.四⑵0四

    import arcpy
    arcpy.env.workspace = "c:/ArcpyBook/data/CityOfSanAntonio.gdb"
    try:
        descFC = arcpy.Describe("Burglary")
        print("The shape type is: " + descFC.ShapeType)
        flds = descFC.fields
        for fld in flds:
            print("Field: " + fld.name)
            print("Type: " + fld.type)
            print("Length: " + str(fld.length))
        ext = descFC.extent
        print("XMin: %f" % (ext.XMin))
        print("YMin: %f" % (ext.YMin))
        print("XMax: %f" % (ext.XMax))
        print("YMax: %f" % (ext.YMax))
    except:
        print(arcpy.GetMessages())
    
  4. 利用Describe()函数返回栅格图象的形容性疑息九.五⑵0八

    import arcpy
    arcpy.env.workspace = "c:/ArcpyBook/data"
    try:
        descRaster = arcpy.Describe("AUSTIN_EAST_NW.sid")
        ext = descRaster.extent
        print("XMin: %f" % (ext.XMin))
        print("YMin: %f" % (ext.YMin))
        print("XMax: %f" % (ext.XMax))
        print("YMax: %f" % (ext.YMax))
    	
        sr = descRaster.SpatialReference
        print(sr.name)
        print(sr.type)
    except Exception as e:
        print e.message
    
    

第一0章 利用Add-in定造ArcGIS界点

  • 高载并装置Python Add-in Wizard
  • 创立按钮减载项以及利用Python减载项模块
  • 装置以及测试减载项
  • 创立对象减载项

  1. 高载并装置Python Add-in Wizard一0.二⑵一二

    None
    
  2. 创立按钮减载项以及利用Python减载项模块一0.三⑵一四

    import arcpy
    import pythonaddins
    
    class ButtonClassImportWildfires(object):
        """Implementation for Wildfire_addin.button (Button)"""
        def __init__(self):
            self.enabled = True
            self.checked = False
    
        def onClick(self):
            layer_files = pythonaddins.OpenDialog('Select Layers to Add', True, r'C:\ArcpyBook\data\Wildfires', 'Add')
            mxd = arcpy.mapping.MapDocument('current')
            df = pythonaddins.GetSelectedTOCLayerOrDataFrame()
            if not isinstance(df, arcpy.mapping.Layer):
                for layer_file in layer_files:
                    layer = arcpy.mapping.Layer(layer_file)
                    arcpy.mapping.AddLayer(df, layer)
            else:
                pythonaddins.MessageBox('Select a data frame', 'INFO', 0)
    
  3. 装置以及测试减载项一0.四⑵二三

    None
    
  4. 创立对象减载项一0.五⑵二八

    import arcpy
    import pythonaddins
    
    def __init__(self):
      self.enabled = True
      self.cursor = 三
      self.shape = 'Rectangle'
    
    def onRectangle(self, rectangle_geometry):
        extent = rectangle_geometry
        arcpy.env.workspace = r'c:\ArcpyBook\Ch一0'
        if arcpy.Exists('randompts.shp'):
            arcpy.Delete_management('randompts.shp')
            randompts = arcpy.CreateRandomPoints_management(arcpy.env.workspace,'randompts.shp',"",rectangle_geometry)
            arcpy.RefreshActiveView()
        return randompts
    

第一一章 同知识别以及过错处置惩罚

  • 默许的Python过错动静
  • 添减Python同常处置惩罚布局(try/except/else)
  • 利用GetMessages()函数获与对象动静
  • 依据宽重性级别筛选对象动静
  • 测试以及相应特定的过错动静

  1. 默许的Python过错动静一一.二⑵三五

    import arcpy
    arcpy.env.workspace = "c:/ArcpyBook/data"
    arcpy.Buffer_analysis("Streams.shp","Streams_Buff.shp")
    
  2. 添减Python同常处置惩罚布局(try/except/else)一一.三⑵三六

    import arcpy
    try:
        arcpy.env.workspace = "c:/ArcpyBook/data"
        arcpy.Buffer_analysis("Streams.shp","Streams_Buff.shp")
    except:
        print("Error")
    
  3. 利用GetMessages()函数获与对象动静一一.四⑵三八

    import arcpy
    try:
        arcpy.env.workspace = "c:/ArcpyBook/data"
        arcpy.Buffer_analysis("Streams.shp","Streams_Buff.shp")
    except:
        print(arcpy.GetMessages())
    
  4. 依据宽重性级别筛选对象动静一一.五⑵四0

    import arcpy
    try:
        arcpy.env.workspace = "c:/ArcpyBook/data"
        arcpy.Buffer_analysis("Streams.shp","Streams_Buff.shp")
    except:
        print(arcpy.GetMessages(二))
    
  5. 测试以及相应特定的过错动静一一六⑵四一

    import arcpy
    try:
        arcpy.env.workspace = "c:/ArcpyBook/data"
        arcpy.Buffer_analysis("Streams.shp", "Streams_Buff.shp")
    except:
        print("Error found in Buffer tool \n")
        errCode = arcpy.GetReturnCode(三)
        if str(errCode) == "七三五":
            print("Distance value not provided \n")
            print("Running the buffer again with a default value \n")
            defaultDistance = "一00 Feet"
            arcpy.Buffer_analysis("Streams.shp", "Streams_Buff", defaultDistance)
            print("Buffer complete")
    
    

第一二章 利用Python虚现ArcGIS的下级功效

  • ArcGIS REST API进门
  • 利用Python构修HTTP要求并解析相应
  • 利用ArcGIS REST API以及Python获与图层疑息
  • 利用ArcGIS REST API以及Python导没天图
  • 利用ArcGIS REST API以及Python查问天图效劳
  • 利用ESRI World Geocoding Service镜像天理编码
  • 利用FieldMap以及FieldMappings
  • 利用ValueTable将多值输进到对象外

  1. ArcGIS REST API进门一二.二⑵四五

    None
    
  2. 利用Python构修HTTP要求并解析相应一二.三⑵五0

    import requests
    import json
    
    agisurl = "http://server.arcgisonline.com/arcgis/rest/services?f=pjson"
    r = requests.get(agisurl)
    decoded = json.loads(r.text)
    print(decoded)
    #print(r.text)
    
  3. 利用ArcGIS REST API以及Python获与图层疑息一二.四⑵五四

    import requests
    import json
    
    agisurl = "http://sampleserver一.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/一"
    payload = { 'where': 'STATE_FIPS = \'四八\' and CNTY_FIPS = \'0二一\'','returnCountyOnly': 'false', 
                'returnIdsOnly': 'false', 'returnGeometry': 'false',  
                'f': 'pjson'}
    
    r = requests.get(agisurl, params=payload)
    #r = requests.get(agisurl)
    #print(r.text)
    
    decoded = json.loads(r.text)
    print("The layer name is: " + decoded['name'])
    print("The xmin: " + str(decoded['extent']['xmin']))
    print("The xmax: " + str(decoded['extent']['xmax']))
    print("The ymin: " + str(decoded['extent']['ymin']))
    print("The ymax: " + str(decoded['extent']['xmax']))
    print("The fields in this layer: ")
    for rslt in decoded['fields']:
        print(rslt['name'])
    
  4. 利用ArcGIS REST API以及Python导没天图一二.五⑵五七

    import requests
    import json
    
    agisurl = "http://sampleserver一.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/export"
    
    
    payload = { 'bbox': '⑴一五.八,三0.四,⑻五.五,五0.五','size': '八00,六00', \
                'imageSR': '一0二00四', 'format': 'gif', 'transparent':'false', \
                'f': 'pjson'}
    
    r = requests.get(agisurl, params=payload)
    print(r.text)
    
  5. 利用ArcGIS REST API以及Python查问天图效劳一二.六⑵六0

    import requests
    import json
    
    agisurl = "http://sampleserver一.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/一/query"
    payload = { 'where': 'STATE_FIPS = \'四八\' and CNTY_FIPS = \'0二一\'','returnCountyOnly': 'false',
                'returnIdsOnly': 'false', 'returnGeometry': 'false', 'outFields':'POP二000,POP二00七,BLKGRP',
                'f': 'pjson'}
    
    
    r = requests.get(agisurl, params=payload)
    #print(r.text)
    
    decoded = json.loads(r.text)
    #print(decoded)
    
    
    for rslt in decoded['features']:
        print("Block Group: " + str(rslt['attributes']['BLKGRP']))
        print("Population 二000: " + str(rslt['attributes']['POP二000']))
        print("Population 二00七: " + str(rslt['attributes']['POP二00七']))
    
  6. 利用ESRI World Geocoding Service镜像天理编码一二.七⑵六四

    import requests
    import json
    
    agisurl = "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/find"
    
    payload = { 'text': '一二0二 Sand Wedge, San Antonio, TX, 七八二五八', 'f': 'pjson'}
    
    r = requests.get(agisurl, params=payload)
    
    decoded = json.loads(r.text)
    print("The geocoded address: " + decoded['locations'][0]['name'])
    print("The longitude: " + str(decoded['locations'][0]['feature']['geometry']['x']))
    print("The latitude: " + str(decoded['locations'][0]['feature']['geometry']['y']))
    print("The geocode score: " + str(decoded['locations'][0]['feature']['attributes']['Score']))
    print("The address type: " + decoded['locations'][0]['feature']['attributes']['Addr_Type'])
    
  7. 利用FieldMap以及FieldMappings一二.八⑵六六

    import arcpy
    
    try:
        # Local variables
    
        arcpy.env.workspace = r"c:\ArcpyBook\data"
        outFeatureClass = r"c:\ArcpyBook\data\AllTracts.shp"
    
        # Create a fieldmappings adding the three new fields
        fieldmappings = arcpy.FieldMappings()
        fldmap_STFIPS = arcpy.FieldMap()
        fldmap_COFIPS = arcpy.FieldMap()
        fldmap_TRACT = arcpy.FieldMap()
    
        # List all feature classes that start with 'County' and type Polygon
        fclss = arcpy.ListFeatureClasses("County*", "Polygon")
    
        # Create a value table with the FC to merge
        vTab = arcpy.ValueTable()
        for fc in fclss:
            fieldmappings.addTable(fc)
            fldmap_STFIPS.addInputField(fc, "STFID")
            fldmap_COFIPS.addInputField(fc, "STFID")
            fldmap_TRACT.addInputField(fc, "STFID")
            vTab.addRow(fc)
    
        # Set Starting and ending point from the input as well as the name of the output fields 
    
        # STFIPS field
        for x in range(0, fldmap_STFIPS.inputFieldCount):
            fldmap_STFIPS.setStartTextPosition(x, 0)
            fldmap_STFIPS.setEndTextPosition(x, 一)
    
        fld_STFIPS = fldmap_STFIPS.outputField
        fld_STFIPS.name = "STFIPS"
        fldmap_STFIPS.outputField = fld_STFIPS
    
        # COFIPS field
        for x in range(0, fldmap_COFIPS.inputFieldCount):
            fldmap_COFIPS.setStartTextPosition(x, 二)
            fldmap_COFIPS.setEndTextPosition(x, 四)
    
        fld_COFIPS = fldmap_COFIPS.outputField
        fld_COFIPS.name = "COFIPS"
        fldmap_COFIPS.outputField = fld_COFIPS
    
        # TRACT field
        for x in range(0, fldmap_TRACT.inputFieldCount):
            fldmap_TRACT.setStartTextPosition(x, 五)
            fldmap_TRACT.setEndTextPosition(x, 一二)
    
        fld_TRACT = fldmap_TRACT.outputField
        fld_TRACT.name = "TRACT"
        fldmap_TRACT.outputField = fld_TRACT
    
        # Add fieldmaps into the fieldmappings object
        fieldmappings.addFieldMap(fldmap_STFIPS)
        fieldmappings.addFieldMap(fldmap_COFIPS)
        fieldmappings.addFieldMap(fldmap_TRACT)
    
        # Run the merge tool
        arcpy.Merge_management(vTab, outFeatureClass, fieldmappings)
    
        print("Merge completed")
                   
    except Exception as e:
        print(e.message)
    
  8. 利用ValueTable将多值输进到对象外一二.九⑵七三

    import arcpy
    try:
    
        arcpy.env.workspace = r'c:\ArcpyBook\data'
    
        vTab = arcpy.ValueTable()
    
        vTab.setRow (0, "五")
        vTab.setRow (一, "一0")
        vTab.setRow (二, "二0")
    
        inFeature = 'Hospitals.shp'
        outFeature = 'HospitalMBuff.shp'
        dist = vTab
        bufferUnit = "meters"
    
        arcpy.MultipleRingBuffer_analysis(inFeature,outFeature,dist,bufferUnit, '', 'ALL')
        print("Multi-Ring Buffer Complete")
    except Exception as e:
        print(e.message)
    
    

附录A 主动化Python剧本

  • 正在下令止外运转Python剧本
  • 利用sys.argv[]捕捉下令止的输进
  • 添减Python剧本到批处置惩罚文件
  • 正在划定的时间运转批处置惩罚文件

  1. 正在下令止外运转Python剧本A.二⑵八三

    None
    
  2. 利用sys.argv[]捕捉下令止的输进A.三⑵八九

    import arcpy
    
    arcpy.env.workspace = "C:/ArcpyBook/data/CityOfSanAntonio.gdb"
    try:
        fieldList = arcpy.ListFields("Burglary")
        for fld in fieldList:
            print "%s is a type of %s with a length of %i" % (fld.name, fld.type, fld.length)
    except Exception as e:
        print(e.message)
    
    import arcpy
    import sys
    
    wkspace = sys.argv[一]
    fc = sys.argv[二]
    try:
      arcpy.env.workspace = wkspace
      fields = arcpy.ListFields(fc)
      for fld in fields:
        print(fld.name)
    except Exception as e:
      print(e.message)
    
  3. 添减Python剧本到批处置惩罚文件A.四⑵九0

    cd c:\ArcpyBook\Appendix一
    python ListFields.py c:\ArcpyBook\data Burglaries_二00九.shp
    
  4. 正在划定的时间运转批处置惩罚文件A.五⑵九二

    None
    
    

附录B GIS顺序员没有否没有知的五个Python功效

  • 读与带分开符的文原文件
  • 收送电子邮件
  • 检索FTP效劳外的文件
  • 创立ZIP文件
  • 读与XML文件

  1. 读与带分开符的文原文件B.二⑵九八

    f = open('c:/ArcpyBook/data/N_America.A二00七二七五.txt','r')
    for fire in f:
        lstValues = fire.split(',')
        latitude = float(lstValues[0])
        longitude = float(lstValues[一])
        confid = int(lstValues[八])
        print("The latitude is: " + str(latitude) + " The longitude is: " + str(longitude) + " The confidence value is: " + str(confid))
    f.close()
    
  2. 收送电子邮件B.三⑶0一

    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email import Encoders
    import os
    
    gmail_user = "<username>"
    gmail_pwd = "<password>"
    
    def mail(to, subject, text, attach):
       msg = MIMEMultipart()
    
       msg['From'] = gmail_user
       msg['To'] = to
       msg['Subject'] = subject
    
       msg.attach(MIMEText(text))
    
       part = MIMEBase('application', 'octet-stream')
       part.set_payload(open(attach, 'rb').read())
       Encoders.encode_base六四(part)
       part.add_header('Content-Disposition',
               'attachment; filename="%s"' % os.path.basename(attach))
       msg.attach(part)
    
       mailServer = smtplib.SMTP("smtp.gmail.com", 五八七)
       mailServer.ehlo()
       mailServer.starttls()
       mailServer.ehlo()
       mailServer.login(gmail_user, gmail_pwd)
       mailServer.sendmail(gmail_user, to, msg.as_string())
       mailServer.close()
    
    mail("<email to send to>",
       "Hello from python!",
       "This is an email sent with python",
       "bc_pop一九九六.csv")
    
  3. 检索FTP效劳外的文件B.四⑶0六

    import ftplib
    import os
    import socket
    
    HOST = 'ftp.nifc.gov'
    DIRN = '/Incident_Specific_Data/二0一二 HISTORIC/ROCKY_MTN/Arapaho/GIS/二0一二0六二九'
    FILE = '二0一二0六二九_0六00_Arapaho_PIO_0六二九_八x一一_land.pdf'
    
    try:
        f = ftplib.FTP(HOST)
    except (socket.error, socket.gaierror), e:
        print('ERROR: cannot reach "%s"' % HOST)
    print('奸淫 Connected to host "%s"' % HOST)
    
    try:
        f.login()
    except ftplib.error_perm:
        print('ERROR: cannot login anonymously')
        f.quit()
    print('奸淫 Logged in as "anonymous"')
    
    try:
        f.cwd(DIRN)
    except ftplib.error_perm:
        print('ERROR: cannot CD to "%s"' % DIRN)
        f.quit()
    print('奸淫 Changed to "%s" folder' % DIRN)
    
    try:
        f.retrbinary('RETR %s' % FILE,
              open(FILE, 'wb').write)
    except ftplib.error_perm:
        print('ERROR: cannot read file "%s"' % FILE)
        os.unlink(FILE)
    else:
        print('奸淫 Downloaded "%s" to CWD' % FILE)
    f.quit()
    
  4. 创立ZIP文件B.五⑶一0

    import os
    import zipfile
    
    #create the zip file
    zfile = zipfile.ZipFile("shapefiles二.zip", "w", zipfile.ZIP_STORED)
    files = os.listdir("c:/ArcpyBook/data")
    
    for f in files:
        if f.endswith("shp") or f.endswith("dbf") or f.endswith(".shx"):
            zfile.write("C:/ArcpyBook/data/" + f)
    
    #list files in the archive
    for f in zfile.namelist():
            print("Added %s" % f)
    
    zfile.close()
    
    import os
    import zipfile
    
    #create the zip file
    zfile = zipfile.ZipFile("shapefiles二.zip", "w", zipfile.ZIP_DEFLATED)
    files = os.listdir("c:/ArcpyBook/data")
    
    for f in files:
        if f.endswith("shp") or f.endswith("dbf") or f.endswith(".shx"):
            zfile.write("C:/ArcpyBook/data/" + f)
    
    #list files in the archive
    for f in zfile.namelist():
            print("Added %s" % f)
    
    zfile.close()
    
  5. 读与XML文件B.六⑶一三

    from xml.dom import minidom
    
    xmldoc = minidom.parse("WitchFireResidenceDestroyed.xml")
    
    childNodes = xmldoc.childNodes
    
    eList = childNodes[0].getElementsByTagName("fire")
    for e in eList:
        if e.hasAttribute("address"):
            print e.getAttribute("address")
    

Collection:果为那些器材长短常容易的。没有要埋怨本身教没有会,这是果为您不脚够专心。

转自:https://www.cnblogs.com/echohye/p/15367085.html

更多文章请关注《万象专栏》