How to create polygon shapefile from a list of coordinates using python gdal/ogr?

You are getting that error because you have the ShapeFile open. So it cannot recreate it.

But I ran your script and got a different error:

Traceback (most recent call last):
  File "test.py", line 48, in <module>
    main(coords, out_shp)
  File "test.py", line 43, in main
    write_shapefile(poly, out_shp)
  File "test.py", line 32, in write_shapefile
    geom = ogr.CreateGeometryFromWkb(poly.wkb)
AttributeError: 'str' object has no attribute 'wkb'

You seem to be trying to extract Well Known Binary (WKB) from Well Know Text (WKT).

You already get the WKT representation from:

    return poly.ExportToWkt()

So to fix it just use the Wkt geometry creator instead of the Wkb.

Change:

geom = ogr.CreateGeometryFromWkb(poly.wkb)

To:

geom = ogr.CreateGeometryFromWkt(poly)

Your datasource (ds) is not created, possibly because you ask for a Esri Shapefile instead of a ESRI Shapefile. In general you should check you get a driver * datastore back from

driver = ogr.GetDriverByName('Esri Shapefile')
ds = driver.CreateDataSource(out_shp)