### Writing a 3D polygon example Source: https://github.com/geospatialpython/pyshp/blob/master/changelog.txt Example demonstrating how to write a 3D polygon. ```python import shapefile # Create a new shapefile writer w = shapefile.Writer("output/test.shp") # Define the shape type for 3D polygons w.shapeType = shapefile.POLYGONM # or shapefile.POLYGONZ # Add a field for a name w.field('NAME', 'C') # Add a 3D polygon with a part and a hole # The parts define the boundaries of the polygon and any holes within it. # The first part is the outer boundary, subsequent parts are holes. # The coordinates are (x, y, z, m) where z is the elevation and m is the measure. w.poly([[[1,1],[1,2],[2,2],[2,1],[1,1]], [[1.2,1.2],[1.8,1.2],[1.8,1.8],[1.2,1.8],[1.2,1.2]]], shapeType=shapefile.POLYGONM) # Add a record for the polygon w.record('3D Polygon Example') # Save the shapefile w.close() print("3D polygon shapefile created successfully.") ``` -------------------------------- ### Run Doctests from an Installed Wheel Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Command to test an installed PyShp wheel against doctests. ```shell python test_shapefile.py ``` -------------------------------- ### 3D MultiPatch Shapefiles Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Example of creating a MultiPatch shapefile with TRIANGLE_STRIP and TRIANGLE_FAN parts. ```python >>> from shapefile import TRIANGLE_STRIP, TRIANGLE_FAN >>> w = shapefile.Writer('shapefiles/test/multipatch') >>> w.field('name', 'C') >>> w.multipatch([ ... [[0,0,0],[0,0,3],[5,0,0],[5,0,3],[5,5,0],[5,5,3],[0,5,0],[0,5,3],[0,0,0],[0,0,3]], # TRIANGLE_STRIP for house walls ... [[2.5,2.5,5],[0,0,3],[5,0,3],[5,5,3],[0,5,3],[0,0,3]], # TRIANGLE_FAN for pointed house roof ... ], ... partTypes=[TRIANGLE_STRIP, TRIANGLE_FAN]) # one type for each part >>> w.record('house1') >>> w.close() ``` -------------------------------- ### Adding Records and Points Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Example demonstrating how to add records and points sequentially to a shapefile writer. ```python >>> w = shapefile.Writer('shapefiles/test/balancing', shapeType=shapefile.POINT) >>> w.field("field1", "C") >>> w.field("field2", "C") >>> w.record("row", "one") >>> w.point(1, 1) >>> w.record("row", "two") >>> w.point(2, 2) ``` -------------------------------- ### Enabling Auto Balance Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Example showing how to enable the autoBalance feature to ensure shape and record counts match. ```python >>> w.autoBalance = 1 >>> w.record("row", "three") >>> w.record("row", "four") >>> w.point(4, 4) >>> w.recNum == w.shpNum True ``` -------------------------------- ### Python __geo_interface__ Example Source: https://github.com/geospatialpython/pyshp/wiki/Home Example of accessing the __geo_interface__ attribute of a shape object. ```python >>> s = sf.shape(0) >>> s.__geo_interface__["type"] 'MultiPolygon' ``` -------------------------------- ### Setup Local File Server for Network Tests Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Steps to clone test files, serve them locally, and run network tests. ```shell git clone http://github.com/JamesParrott/PyShp_test_shapefile cd PyShp_test_shapefile python -m http.server 8000 ``` -------------------------------- ### Loading a large shapefile Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Example of loading a large shapefile from a URL using the shapefile.Reader. ```python >>> sf = shapefile.Reader("https://archive.org/download/ne_10m_admin_1_states_provinces/ne_10m_admin_1_states_provinces.zip") ``` -------------------------------- ### Manual Balancing Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Example of manually balancing the shapefile writer by calling the balance() method. ```python >>> w.autoBalance = 0 >>> w.record("row", "five") >>> w.record("row", "six") >>> w.record("row", "seven") >>> w.point(5, 5) >>> w.point(6, 6) >>> w.balance() >>> w.recNum == w.shpNum True ``` -------------------------------- ### Get all records Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Retrieves a list of all records from the shapefile. ```python >>> records = sf.records() >>> len(records) 663 ``` -------------------------------- ### Get a list of shapes Source: https://github.com/geospatialpython/pyshp/wiki/Home Demonstrates how to retrieve a list of all Shape objects from a shapefile. ```python >>> shapes = sf.shapes() ``` -------------------------------- ### Editing shapefiles: Copying a subset of fields Source: https://github.com/geospatialpython/pyshp/blob/master/README.md This example demonstrates how to create a new shapefile containing only a subset of fields from an existing shapefile. ```python >>> # create writer >>> w = shapefile.Writer('shapefiles/test/edit') >>> # define which fields to keep >>> keep_fields = ['BKG_KEY', 'MEDIANRENT'] >>> # copy over the relevant fields from the reader >>> r = shapefile.Reader("shapefiles/blockgroups") >>> for field in r.fields[1:]: ... if field[0] in keep_fields: ... w.field(*field) >>> # write only the relevant attribute values >>> for shapeRec in r.iterShapeRecords(fields=keep_fields): ... w.record(*shapeRec.record) ... w.shape(shapeRec.shape) >>> # close writer >>> w.close() ``` -------------------------------- ### Shapefiles with measurement (M) values Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Example of creating a shapefile with M-values, including handling omitted and missing M-values. ```python >>> w = shapefile.Writer('shapefiles/test/linem') >>> w.field('name', 'C') >>> w.linem([ ... [[1,5,0],[5,5],[5,1,3],[3,3,None],[1,1,0]], # line with one omitted and one missing M-value ... [[3,2],[2,6]] # line without any M-values ... ]) >>> w.record('linem1') >>> w.close() ``` -------------------------------- ### Reading All Records Source: https://github.com/geospatialpython/pyshp/wiki/Home Shows how to get a list of all records from a shapefile using the records() method. ```python >>> records = sf.records() >>> len(records) 663 ``` -------------------------------- ### Shapefiles with elevation (Z) values Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Example of creating a shapefile with Z-values, including handling omitted Z-values and combined Z- and M-values. ```python >>> w = shapefile.Writer('shapefiles/test/linez') >>> w.field('name', 'C') >>> w.linez([ ... [[1,5,18],[5,5,20],[5,1,22],[3,3],[1,1]], # line with some omitted Z-values ... [[3,2],[2,6]], # line without any Z-values ... [[3,2,15,0],[2,6,13,3],[1,9,14,2]] # line with both Z- and M-values ... ]) >>> w.record('linez1') >>> w.close() ``` -------------------------------- ### ShapeRecord Usage Example Source: https://github.com/geospatialpython/pyshp/wiki/ShapeRecords Demonstrates how to use the shapeRecords() method to access geometry and attributes, and iterate through all records in a shapefile. ```python >>> import shapefile >>> r = shapefile.Reader("addr") >>> sr = r.shapeRecords() >>> # get the first shaperecord >>> sr_test = sr[0] >>> # Look at the geometry of the shape >>> sr_test.shape.points [[-89.522996, 34.363596]] >>> # Look at the attributes of the dbf record >>> sr_test.record ['718 South 8', 'Oxford', 'MS', '38655'] >>> # Now let’s iterate through all of them >>> for sr in r.shapeRecords(): ... print "x: ", sr.points[0][0] ... print "y: ", sr.points[0][1] ... # Output just the address field ... print "Address: ", sr.record[0] x: -89.522996 y: 34.363596 Address: 718 South 8th x: -89.520695 y: 34.360863 Address: 1195 South 11th x: -89.520927 y: 34.362924 Address: 805 Fillmore Ave ``` -------------------------------- ### Merging Multiple Shapefiles Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Example of merging multiple shapefiles by iterating through source files to avoid loading everything into memory. ```python # create writer w = shapefile.Writer('shapefiles/test/merge') # copy over fields from the reader r = shapefile.Reader("shapefiles/blockgroups") for field in r.fields[1:]: w.field(*field) # copy the shapefile to writer 10 times repeat = 10 for i in range(repeat): r = shapefile.Reader("shapefiles/blockgroups") for shapeRec in r.iterShapeRecords(): w.record(*shapeRec.record) w.shape(shapeRec.shape) # check that the written file is 10 times longer len(w) == len(r) * 10 # close the writer w.close() ``` -------------------------------- ### Iterating through shape records in a large shapefile Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Provides an example of iterating through both shapes and records simultaneously in a large shapefile for efficient processing. ```python >>> for shapeRec in sf.iterShapeRecords(): ... # do something here ... pass ``` -------------------------------- ### Creating Attributes - Keyword Arguments Source: https://github.com/geospatialpython/pyshp/wiki/Home Demonstrates adding attributes using keyword arguments for field names. ```python >>> w = shapefile.Writer(shapefile.POLYLINE) >>> w.line(parts=[[[1,5],[5,5],[5,1],[3,3],[1,1]]]) >>> w.field('FIRST_FLD','C','40') >>> w.field('SECOND_FLD','C','40') >>> w.record(FIRST_FLD='First', SECOND_FLD='Line') >>> w.save('shapefiles/test/line') ``` -------------------------------- ### Get bounding box Source: https://github.com/geospatialpython/pyshp/wiki/Home Retrieves the bounding box coordinates for a shape. ```python >>> # Get the bounding box of the 4th shape. >>> # Round coordinates to 3 decimal places >>> bbox = shapes[3].bbox >>> ['%.3f' % coord for coord in bbox] ['-122.486', '37.787', '-122.446', '37.811'] ``` -------------------------------- ### Get shape type Source: https://github.com/geospatialpython/pyshp/wiki/Home Retrieves the integer representing the type of shape. ```python >>> shapes[3].shapeType 5 ``` -------------------------------- ### Get a single record Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Retrieves a specific record by its index. ```python >>> rec = sf.record(3) ``` -------------------------------- ### Run Network Doctests with Local Server Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Command to run doctests with network tests using a local file server. ```bash REPLACE_REMOTE_URLS_WITH_LOCALHOST=yes && python test_shapefile.py ``` -------------------------------- ### Get shape points Source: https://github.com/geospatialpython/pyshp/wiki/Home Retrieves the list of (x,y) coordinates for all points in a shape. ```python >>> len(shapes[3].points) 173 >>> # Get the 8th point of the fourth shape >>> # Truncate coordinates to 3 decimal places >>> shape = shapes[3].points[7] >>> ['%.3f' % coord for coord in shape] ['-122.471', '37.787'] ``` -------------------------------- ### Create a Writer instance Source: https://github.com/geospatialpython/pyshp/wiki/Home Instantiate the Writer class to begin creating a shapefile. ```python w = shapefile.Writer() ``` -------------------------------- ### Creating Text Fields Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Shows how to create text fields ('C' type) with customizable sizes and add records. ```python >>> w = shapefile.Writer('shapefiles/test/dtype') >>> w.field('TEXT', 'C') >>> w.field('SHORT_TEXT', 'C', size=5) >>> w.field('LONG_TEXT', 'C', size=250) >>> w.null() >>> w.record('Hello', 'World', 'World'*50) >>> w.close() >>> r = shapefile.Reader('shapefiles/test/dtype') >>> assert r.record(0) == ['Hello', 'World', 'World'*50] >>> r.close() ``` -------------------------------- ### Reading Shapefile Meta-Data Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Demonstrates how to read shapefile metadata such as shape type, number of features, and bounding box. ```python sf = shapefile.Reader("shapefiles/blockgroups.dbf") sf.shapeType # Expected output: 5 ``` ```python sf.shapeType == shapefile.POLYGON # Expected output: True ``` ```python sf.shapeTypeName == 'POLYGON' # Expected output: True ``` ```python len(sf) # Expected output: 663 ``` ```python sf.bbox # Expected output: BBox(xmin=-122.515048, ymin=37.652916, xmax=-122.327622, ymax=37.863433) ``` ```python sf.__geo_interface__['type'] # Expected output: 'FeatureCollection' ``` -------------------------------- ### Get shape parts Source: https://github.com/geospatialpython/pyshp/wiki/Home Retrieves the indices of the first point of each part within a shape. ```python >>> shapes[3].parts [0] ``` -------------------------------- ### Import the library Source: https://github.com/geospatialpython/pyshp/wiki/Home Before doing anything you must import the library. ```python >>> import shapefile ``` -------------------------------- ### Creating Attributes - Point Shapefile Source: https://github.com/geospatialpython/pyshp/wiki/Home Demonstrates creating a point shapefile with fields and records. ```python >>> w = shapefile.Writer(shapefile.POINT) >>> w.point(1,1) >>> w.point(3,1) >>> w.point(4,3) >>> w.point(2,2) >>> w.field('FIRST_FLD') >>> w.field('SECOND_FLD','C','40') >>> w.record('First','Point') >>> w.record('Second','Point') >>> w.record('Third','Point') >>> w.record('Fourth','Point') >>> w.save('shapefiles/test/point') ``` -------------------------------- ### Saving to File-Like Objects Source: https://github.com/geospatialpython/pyshp/wiki/Home Demonstrates writing shapefiles to file-like objects using StringIO. ```python >>> try: ... from StringIO import StringIO ... except ImportError: ... from io import BytesIO as StringIO >>> shp = StringIO() >>> shx = StringIO() >>> dbf = StringIO() >>> w.saveShp(shp) >>> w.saveShx(shx) >>> w.saveDbf(dbf) >>> # Normally you would call the "StringIO.getvalue()" method on these objects. >>> shp = shx = dbf = None ``` -------------------------------- ### Accessing Shape Type Name Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Getting the string representation of the shape type. ```python shapes[3].shapeTypeName ``` -------------------------------- ### Accessing Shape Type Integer Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Getting the integer representation of the shape type. ```python shapes[3].shapeType ``` -------------------------------- ### Adding Attributes Using Keyword Arguments Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Demonstrates adding records to a shapefile using keyword arguments where keys are field names. ```python >>> w = shapefile.Writer('shapefiles/test/dtype') >>> w.field('FIRST_FLD','C', 40) >>> w.field('SECOND_FLD','C', 40) >>> w.null() >>> w.null() >>> w.record('First', 'Line') >>> w.record(FIRST_FLD='First', SECOND_FLD='Line') >>> w.close() ``` -------------------------------- ### Get field names Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Extracts field names from the shapefile object, excluding the DeletionFlag. ```python >>> fieldnames = [f[0] for f in sf.fields[1:]] ``` -------------------------------- ### Accessing Shape Parts Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Getting the indices of the first point of each part within a shape. ```python shapes[3].parts ``` -------------------------------- ### Creating Date Fields Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Demonstrates creating date fields ('D' type) and adding records using date objects, lists, or strings. ```python >>> from datetime import date >>> w = shapefile.Writer('shapefiles/test/dtype') >>> w.field('DATE', 'D') >>> w.null() >>> w.null() >>> w.null() >>> w.null() >>> w.record(date(1898,1,30)) >>> w.record([1998,1,30]) >>> w.record('19980130') >>> w.record(None) >>> w.close() >>> r = shapefile.Reader('shapefiles/test/dtype') >>> assert r.record(0) == [date(1898,1,30)] >>> assert r.record(1) == [date(1998,1,30)] >>> assert r.record(2) == [date(1998,1,30)] >>> assert r.record(3) == [None] >>> r.close() ``` -------------------------------- ### Creating Attributes - Polygon Shapefile Source: https://github.com/geospatialpython/pyshp/wiki/Home Demonstrates creating a polygon shapefile with fields and records. ```python >>> w = shapefile.Writer(shapefile.POLYGON) >>> w.poly(parts=[[[1,5],[5,5],[5,1],[3,3],[1,1]]]) >>> w.field('FIRST_FLD','C','40') >>> w.field('SECOND_FLD','C','40') >>> w.record('First','Polygon') >>> w.save('shapefiles/test/polygon') ``` -------------------------------- ### Run Network Tests with Local Server Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Command to run pytest with network tests using a local file server. ```bash REPLACE_REMOTE_URLS_WITH_LOCALHOST=yes && pytest ``` -------------------------------- ### Creating Attributes - Polyline Shapefile Source: https://github.com/geospatialpython/pyshp/wiki/Home Demonstrates creating a polyline shapefile with fields and records. ```python >>> w = shapefile.Writer(shapefile.POLYLINE) >>> w.line(parts=[[[1,5],[5,5],[5,1],[3,3],[1,1]]]) >>> w.poly(parts=[[[1,3],[5,3]]], shapeType=shapefile.POLYLINE) >>> w.field('FIRST_FLD','C','40') >>> w.field('SECOND_FLD','C','40') >>> w.record('First','Line') >>> w.record('Second','Line') >>> w.save('shapefiles/test/line') ``` -------------------------------- ### Disabling Verbose Logging Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Example of how to disable verbose logging in PyShp by setting the VERBOSE constant to False. ```python >>> shapefile.VERBOSE = False ``` -------------------------------- ### Reading Geometry Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Demonstrates how to read the geometry of shapes from a shapefile. ```python shapes = sf.shapes() ``` ```python len(shapes) # Expected output: 663 ``` ```python s = sf.shape(7) s # Expected output: Polygon #7 ``` ```python # Read the bbox of the 8th shape to verify # Round coordinates to 3 decimal places ['%.3f' % coord for coord in s.bbox] # Expected output: ['-122.450', '37.801', '-122.442', '37.808'] ``` -------------------------------- ### Run Pytest Unit Tests Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Command to run the pytest unit tests from the command line. ```shell python -m pytest ``` -------------------------------- ### Get original object ID Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Retrieves the original index position of the record in the shapefile using the 'oid' attribute. ```python >>> rec.oid 3 ``` -------------------------------- ### Writing Shapefiles to Local Files Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Initiating a new Writer instance to create a shapefile and save it to a local file path. ```python >>> w = shapefile.Writer('shapefiles/test/testfile') >>> w.field('field1', 'C') ``` ```python >>> w = shapefile.Writer(dbf='shapefiles/test/onlydbf.dbf') >>> w.field('field1', 'C') ``` -------------------------------- ### Creating a new field Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Demonstrates how to create a new field object using the Field.from_unchecked method, specifying the name, type, size, and decimal places. ```python >>> shapefile.Field.from_unchecked("Population", "N", 10,0) Field(name="Population", field_type=FieldType.N, size=10, decimal=0) ``` -------------------------------- ### Run Doctests from shapefile.py Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Command to run the doctests embedded within the shapefile.py file. ```shell python shapefile.py ``` -------------------------------- ### Examining Z-type shapefiles Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Demonstrates how to examine Z-values in a shapefile, including accessing the ZBox and individual Z-values. ```python >>> r = shapefile.Reader('shapefiles/test/linez') >>> r.zbox # the lower and upper bound of Z-values in the shapefile ZBox(zmin=0.0, zmax=22.0) >>> r.shape(0).z # flat list of Z-values [18.0, 20.0, 22.0, 0.0, 0.0, 0.0, 0.0, 15.0, 13.0, 14.0] >>> r.close() ``` -------------------------------- ### Examining Shapefiles with M-values Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Demonstrates how to examine M-values in a shapefile, including accessing the MBox and individual M-values. ```python >>> r = shapefile.Reader('shapefiles/test/linem') >>> r.mbox # the lower and upper bound of M-values in the shapefile MBox(mmin=0.0, mmax=3.0) >>> r.shape(0).m # flat list of M-values [0.0, None, 3.0, None, 0.0, None, None] >>> r.close() ``` -------------------------------- ### Reading Shapefiles from Local Files (Specific Extension with Keyword Arguments) Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Specify which file extensions to read using keyword arguments. ```python >>> sf = shapefile.Reader(dbf="shapefiles/blockgroups.dbf") ``` -------------------------------- ### Writing Shapefiles Using the Context Manager Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Using the Writer class as a context manager to ensure files are properly closed. ```python >>> w.close() >>> with shapefile.Writer("shapefiles/test/contextwriter") as w: ... w.field('field1', 'C') ... pass ``` -------------------------------- ### Writing Shapefiles to File-Like Objects Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Writing shapefiles to Python file-like objects using StringIO. ```python >>> try: ... from StringIO import StringIO ... except ImportError: ... from io import BytesIO as StringIO >>> shp = StringIO() >>> shx = StringIO() >>> dbf = StringIO() >>> w = shapefile.Writer(shp=shp, shx=shx, dbf=dbf) >>> w.field('field1', 'C') >>> w.record() >>> w.null() >>> w.close() >>> # To read back the files you could call the "StringIO.getvalue()" method later. >>> assert shp.getvalue() >>> assert shx.getvalue() >>> assert dbf.getvalue() >>> # In fact, you can read directly from them using the Reader >>> r = shapefile.Reader(shp=shp, shx=shx, dbf=dbf) >>> len(r) 1 ``` -------------------------------- ### Writing a .prj file Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Python code to create a .prj file with a WGS 84 projection string. ```python with open("{}.prj".format(filename), "w") as prj: wkt = 'GEOGCS["WGS 84",' wkt += 'DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563]]' wkt += ',PRIMEM["Greenwich",0], UNIT["degree",0.0174532925199433]]' prj.write(wkt) ``` -------------------------------- ### Reading Geometry and Records Simultaneously Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Demonstrates how to read geometry and attributes together using shapeRecord() and shapeRecords(). ```python >>> shapeRecs = sf.shapeRecords() >>> shapeRecs[3].record[1:3] ['060750601001', 4715] >>> shapeRecs.__geo_interface__['type'] 'FeatureCollection' >>> shapeRec = sf.shapeRecord(3) >>> shapeRec.record[1:3] ['060750601001', 4715] >>> shapeRec.__geo_interface__['type'] 'Feature' ``` -------------------------------- ### Skip Network Tests with Doctests Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Command to skip network-related tests when running doctests. ```shell python test_shapefile.py -m "not network" ``` -------------------------------- ### Creating Boolean Fields Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Shows how to create boolean fields ('L' type) and add records with True, False, 1, 0, or None values. ```python >>> w = shapefile.Writer('shapefiles/test/dtype') >>> w.field('BOOLEAN', 'L') >>> w.null() >>> w.null() >>> w.null() >>> w.null() >>> w.null() >>> w.null() >>> w.record(True) >>> w.record(1) >>> w.record(False) >>> w.record(0) >>> w.record(None) >>> w.record("Nonsense") >>> w.close() >>> r = shapefile.Reader('shapefiles/test/dtype') >>> r.record(0) Record #0: [True] >>> r.record(1) Record #1: [True] >>> r.record(2) Record #2: [False] >>> r.record(3) Record #3: [False] >>> r.record(4) Record #4: [None] >>> r.record(5) Record #5: [None] >>> r.close() ``` -------------------------------- ### Creating Numeric Fields Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Illustrates creating numeric fields ('N' or 'F' type) with varying precision and large number handling. ```python >>> w = shapefile.Writer('shapefiles/test/dtype') >>> w.field('INT', 'N') >>> w.field('LOWPREC', 'N', decimal=2) >>> w.field('MEDPREC', 'N', decimal=10) >>> w.field('HIGHPREC', 'N', decimal=30) >>> w.field('FTYPE', 'F', decimal=10) >>> w.field('LARGENR', 'N', 101) >>> nr = 1.3217328 >>> w.null() >>> w.null() >>> w.record(INT=nr, LOWPREC=nr, MEDPREC=nr, HIGHPREC=-3.2302e-25, FTYPE=nr, LARGENR=int(nr)*10**100) >>> w.record(None, None, None, None, None, None) >>> w.close() >>> r = shapefile.Reader('shapefiles/test/dtype') >>> assert r.record(0) == [1, 1.32, 1.3217328, -3.2302e-25, 1.3217328, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000] >>> assert r.record(1) == [None, None, None, None, None, None] >>> r.close() ``` -------------------------------- ### Setting Shape Type on Writer Creation Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Demonstrates how to set the shape type when initializing a shapefile.Writer object. ```python >>> w = shapefile.Writer('shapefiles/test/shapetype', shapeType=3) >>> w.field('field1', 'C') >>> w.shapeType 3 ``` -------------------------------- ### Writing a shapefile with UTF-8 encoding Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Shows how to write a shapefile using UTF-8 encoding, preserving the original data while converting from a different encoding (e.g., Latin-1). ```python >>> w = shapefile.Writer("shapefiles/test/latin_as_utf8.shp", encoding="utf8") >>> w.fields = r.fields[1:] >>> w.record(*r.record(0)) >>> w.null() >>> r.close() >>> w.close() ``` -------------------------------- ### Reading a Single Record Source: https://github.com/geospatialpython/pyshp/wiki/Home Shows how to read a single record by its index using the record() method. ```python >>> rec = sf.record(3) >>> rec[1:3] ['060750601001', 4715] ``` -------------------------------- ### Adding a Polygon shape Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Explains and shows how to add Polygon shapes, which consist of multiple polygons. Polygons must have at least 4 points, and the last point must be the same as the first. It also covers ordering for polygons and holes. ```python >>> w = shapefile.Writer('shapefiles/test/polygon') >>> w.field('name', 'C') >>> w.poly([ ... [[113,24], [112,32], [117,36], [122,37], [118,20]], # poly 1 ... [[116,29],[116,26],[119,29],[119,32]], # hole 1 ... [[15,2], [17,6], [22,7]] # poly 2 ... ]) >>> w.record('polygon1') >>> w.close() ``` -------------------------------- ### Handling encoding errors by replacing characters Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Illustrates how to handle encoding errors by replacing problematic characters with a placeholder when the correct encoding cannot be determined. ```python >>> r = shapefile.Reader("shapefiles/latin1.shp", encoding="ascii", encodingErrors="replace") >>> r.record(0) == [2, u'�and�'] True >>> r.close() ``` -------------------------------- ### Run Only Network Tests with Doctests Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Command to run only network-related tests with doctests. ```shell python shapefile.py -m network ``` -------------------------------- ### Accessing Fields Source: https://github.com/geospatialpython/pyshp/wiki/Home Demonstrates how to access the field names and their properties from a shapefile reader object. ```python >>> fields = sf.fields >>> assert fields == [("DeletionFlag", "C", 1, 0), ["AREA", "N", 18, 5], ... ["BKG_KEY", "C", 12, 0], ["POP1990", "N", 9, 0], ["POP90_SQMI", "N", 10, 1], ... ["HOUSEHOLDS", "N", 9, 0], ... ["MALES", "N", 9, 0], ["FEMALES", "N", 9, 0], ["WHITE", "N", 9, 0], ... ["BLACK", "N", 8, 0], ["AMERI_ES", "N", 7, 0], ["ASIAN_PI", "N", 8, 0], ... ["OTHER", "N", 8, 0], ["HISPANIC", "N", 8, 0], ["AGE_UNDER5", "N", 8, 0], ... ["AGE_5_17", "N", 8, 0], ["AGE_18_29", "N", 8, 0], ["AGE_30_49", "N", 8, 0], ... ["AGE_50_64", "N", 8, 0], ["AGE_65_UP", "N", 8, 0], ... ["NEVERMARRY", "N", 8, 0], ["MARRIED", "N", 9, 0], ["SEPARATED", "N", 7, 0], ... ["WIDOWED", "N", 8, 0], ["DIVORCED", "N", 8, 0], ["HSEHLD_1_M", "N", 8, 0], ... ["HSEHLD_1_F", "N", 8, 0], ["MARHH_CHD", "N", 8, 0], ... ["MARHH_NO_C", "N", 8, 0], ["MHH_CHILD", "N", 7, 0], ... ["FHH_CHILD", "N", 7, 0], ["HSE_UNITS", "N", 9, 0], ["VACANT", "N", 7, 0], ... ["OWNER_OCC", "N", 8, 0], ["RENTER_OCC", "N", 8, 0], ... ["MEDIAN_VAL", "N", 7, 0], ["MEDIANRENT", "N", 4, 0], ... ["UNITS_1DET", "N", 8, 0], ["UNITS_1ATT", "N", 7, 0], ["UNITS2", "N", 7, 0], ... ["UNITS3_9", "N", 8, 0], ["UNITS10_49", "N", 8, 0], ... ["UNITS50_UP", "N", 8, 0], ["MOBILEHOME", "N", 7, 0]] ``` -------------------------------- ### Adding a Point shape Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Shows how to add a point shape to a shapefile using x and y coordinates. ```python >>> w = shapefile.Writer('shapefiles/test/point') >>> w.field('name', 'C') >>> w.point(122, 37) >>> w.record('point1') >>> w.close() ``` -------------------------------- ### Iterating through records in a large shapefile Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Shows how to iterate through records in a large shapefile efficiently, processing one record at a time. ```python >>> for rec in sf.iterRecords(): ... # do something here ... pass ``` -------------------------------- ### Reading Shapefiles from File-Like Objects Source: https://github.com/geospatialpython/pyshp/wiki/Home You can also load shapefiles from any Python file-like object using keyword arguments to specify any of the three files. This feature is very powerful and allows you to load shapefiles from a url, from a zip file, serialized object, or in some cases a database. ```python >>> myshp = open("shapefiles/blockgroups.shp", "rb") >>> mydbf = open("shapefiles/blockgroups.dbf", "rb") >>> r = shapefile.Reader(shp=myshp, dbf=mydbf) ``` -------------------------------- ### Reading Shapefiles Source: https://github.com/geospatialpython/pyshp/wiki/Home To read a shapefile create a new "Reader" object and pass it the name of an existing shapefile. The shapefile format is acutally a collection of three files. You specify the base filename of the shapefile or the complete filename of any of the shapefile component files. ```python >>> sf = shapefile.Reader("shapefiles/blockgroups") ``` ```python >>> sf = shapefile.Reader("shapefiles/blockgroups.shp") ``` ```python >>> sf = shapefile.Reader("shapefiles/blockgroups.dbf") ``` -------------------------------- ### Adding a Null shape Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Demonstrates how to add a null shape to a shapefile when geometry is not available for a record. ```python >>> w = shapefile.Writer('shapefiles/test/null') >>> w.field('name', 'C') >>> w.null() >>> w.record('nullgeom') >>> w.close() ``` -------------------------------- ### Reading All Shape Records Simultaneously Source: https://github.com/geospatialpython/pyshp/wiki/Home Demonstrates using the shapeRecords() method to retrieve both geometry and attributes for all shapes. ```python >>> shapeRecs = sf.shapeRecords() >>> shapeRecs3.record[1:3] ['060750601001', 4715] >>> points = shapeRecs[3].shape.points[0:2] >>> len(points) 2 ``` -------------------------------- ### Using the Reader as a Context Manager Source: https://github.com/geospatialpython/pyshp/blob/master/README.md The Reader class can be used as a context manager to ensure that open file objects are properly closed after reading. ```python >>> with shapefile.Reader("shapefiles/blockgroups.shp") as shp: ... print(shp) shapefile Reader 663 shapes (type 'POLYGON') 663 records (44 fields) ``` -------------------------------- ### Reading Shapefiles from Local Files (Base Name) Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Create a Reader object by passing the base filename of the shapefile. ```python >>> sf = shapefile.Reader("shapefiles/blockgroups") ``` -------------------------------- ### Setting Shape Type After Writer Creation Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Demonstrates how to set the shape type for an existing shapefile.Writer object. ```python >>> w.shapeType = 1 >>> w.shapeType 1 ``` -------------------------------- ### Reading a Single Shape Record Source: https://github.com/geospatialpython/pyshp/wiki/Home Illustrates how to read a single shape/record pair using the shapeRecord() method with an index. ```python >>> shapeRec = sf.shapeRecord(3) >>> shapeRec.record[1:3] ['060750601001', 4715] >>> points = shapeRec.shape.points[0:2] >>> len(points) 2 ``` -------------------------------- ### Reading Shapefiles from Local Files (Specific Extension) Source: https://github.com/geospatialpython/pyshp/blob/master/README.md Create a Reader object by passing the filename of any component file of the shapefile. The library does not care about file extensions. ```python >>> sf = shapefile.Reader("shapefiles/blockgroups.shp") ``` ```python >>> sf = shapefile.Reader("shapefiles/blockgroups.dbf") ```