Search code examples
pythoncsvshapefiledbf

Converting csv to shp: Duplicate shp for multiple csv


My code is meant to convert .csv files to .shp files. I do not recieve any error messages, and a .shp, .shx, and .dbf file are created for each .csv. However, when I open up the .dbf files, all of them are duplicates of the .dbf created for the first .csv.

Here is my code:

import glob
import csv
import shapefile as shp
Lon, Lat, Count = [],[],[]

for filename in glob.glob('C:/Users/brownk98/Downloads/GLM/Headers/*.csv'):
    revFilename = 
    filename.replace('C:/Users/brownk98/Downloads/GLM/Headers\\*.csv', "")
    rev2Filename = revFilename.replace(".csv", "") 
    out_file = rev2Filename + '_temp.shp'

    with open(rev2Filename + '.csv') as f:
        next(f)
        r = csv.reader(f, delimiter=',')
        #for i,row in enumerate(r):
        for row in r:
            #if i > 0: #skip header
            Lon.append(float(row[0]))
            Lat.append(float(row[1]))
            Count.append(int(row[2]))

        #f.close()
    w = shp.Writer(shp.POINT)
    w.autoBalance = 1 #ensures gemoetry and attributes match
    w.field('Lon', "F",10,10)
    w.field('Lat',"F",10,10)
    w.field('Count',"N",10)

    for j,k in enumerate(Lat):
        w.point(Lon[j],Lat[j]) #write the geometry
        w.record(Lon[j], Lat[j], Count[j]) #write the attributes
    w.save(out_file)

Example of the Duplicates: First File

Lon                 Lat         Count
-135.0000000000 0.0000000000    13320
-135.1523800000 0.3345030000    3
-135.3058900000 0.6699620000    9
-135.4605200000 1.0063680000    61
-135.6163000000 1.3437130000    99
-135.7732400000 1.6819870000    31

Second File(all other files look like this as well)

Lon                      Lat    Count
-135.0000000000 0.0000000000    13320
-135.1523800000 0.3345030000    3
-135.3058900000 0.6699620000    9
-135.4605200000 1.0063680000    61
-135.6163000000 1.3437130000    99
-135.7732400000 1.6819870000    31

File two should have different counts for the lon, lats than file one, but my code just seems to be copying the counts from the first file into all the subsequent files. How can I fix this? Any help would be appreciated!


Solution

  • Question: ... seems to be copying the counts from the first file into all the subsequent files ...

    You have to initalize Lon, Lat, Count = [],[],[] for every File.

    Change the following:

    ...
    for filename in glob.glob('C:/Users/brownk98/Downloads/GLM/Headers/*.csv'):
    
        ...
    
        with open(rev2Filename + '.csv') as f:
            next(f)
            r = csv.reader(f, delimiter=',')
    
            Lon, Lat, Count = [],[],[]
    
            for row in r:
                ...