out_feat.SetField('X_default', pt.GetX()) out_feat.SetField('Y_default', pt.GetY()) out_feat.SetField('X_short', pt.GetX()) out_feat.SetField('Y_short', pt.GetY()) out_lyr.CreateFeature(out_feat) ######################## 3.6 Updating existing data ######################### # Set things up for the following examples. original_fn = os.path.join(data_dir, 'Washington', 'large_cities.shp') new_fn = os.path.join(data_dir, 'output', 'large_cities2.shp') # First make a copy of a shapefile so you have something to test things on. pb.copy_datasource(original_fn, new_fn) # Open the copied shapefile for writing. ds = ogr.Open(new_fn, 1) if ds is None: sys.exit('Could not open {0}.'.format(new_fn)) lyr = ds.GetLayer(0) # Take a look at the attributes before you change anything. print('Original attributes') pb.print_attributes(lyr, geom=False) #################### 3.6.1 Changing the layer definition #################### # Change the name of the "Name" attribute field by creating a new field
######################## 4.3 Testing capabilities ########################### # Test if you can create a new shapefile in a folder opened for reading only. dirname = os.path.join(data_dir, 'global') ds = ogr.Open(dirname) print(ds.TestCapability(ogr.ODsCCreateLayer)) # Test if you can create a new shapefile in a folder opened for writing. ds = ogr.Open(dirname, 1) print(ds.TestCapability(ogr.ODsCCreateLayer)) # Make a copy of a shapefile for the following examples. original_fn = os.path.join(data_dir, 'Washington', 'large_cities2.shp') new_fn = os.path.join(data_dir, 'output', 'large_cities3.shp') pb.copy_datasource(original_fn, new_fn) # Try opening the datasource read-only and see if you can add a field (you # can't). The example in the book opens it for writing, as in the next # snippet in this file). ds = ogr.Open(new_fn, 0) if ds is None: sys.exit('Could not open {0}.'.format(new_fn)) lyr = ds.GetLayer(0) if not lyr.TestCapability(ogr.OLCCreateField): raise RuntimeError('Cannot create fields.') lyr.CreateField(ogr.FieldDefn('ID', ogr.OFTInteger)) # Now try it with the datasource opened for writing. This is the way the # book does it, because this is how it should be done.