import glob
import os
import shapefile


import urllib, geojson, gdal, subprocess
from dbfpy import dbf
shp_files = glob.glob('*.shp')
print(shp_files)
#r = shapefile.Reader(shp_files)
#w = shapefile.Writer('shp')
# Loop through ONLY the shp files and copy their shapes
# to a writer object. We avoid opening the dbf files
# to prevent any field-parsing errors.cwd = os.getcwd()
w = shapefile.Writer("state_merged/merged_result.shp")
for f in shp_files:
    r = shapefile.Reader(f)
    shapes = r.shape(1)
    records = r.record(0)
    r = geojson.loads(r.read())

    with open('r.geojson', 'w') as fr:
        geojson.dump(r, fr)
    w.shape(r)
    w.record(r)
w.fields = list(r.fields)
w.save(r" state_merged/merged_result.shp")
shpf.close()
# Save only the shp and shx index file to the new
# merged shapefile.
w.saveShp("state_merged/merged_result.shp")
w.saveShx("state_merged/merged_result.shx")
# Now we come back with dbfpy and merge the dbf files
dbf_files = glob.glob("*.dbf")
# Use the first dbf file as a template
template = dbf_files.pop(0)
merged_dbf_name = "merged.dbf"
# Copy the entire template dbf file to the merged file
merged_dbf = open(merged_dbf_name, "wb")
temp = open(template, "rb")
merged_dbf.write(temp.read())
merged_dbf.close()
temp.close()
# Now read each record from teh remaining dbf files
# and use the contents to create a new record in
# the merged dbf file. 
db = dbf.Dbf(merged_dbf_name)
for f in dbf_files:
    print( "Dbf: %s" % f)
    dba = dbf.Dbf(f)
    for rec in dba:
        db_rec = db.newRecord()
        for k,v in rec.asDict().items():
            db_rec[k] = v
        db_rec.store()
db.close()

