dpalm dpalm - 3 months ago 12
Python Question

CSV.writer | Ensure first row in CSV is also last row

This code is going through .KAP files on a shared drive and creating CSV's on my local drive consisting of only the coordinate pairs of lat/lon extisting within the .KAP files.

Example of coordinate lines within a .KAP file

PLY/1,48.107478621032,-69.733975000000
PLY/2,48.163516399836,-70.032838888053
PLY/3,48.270000002883,-70.032838888053
PLY/4,48.107478621032,-69.733975000000


These coordinates will later be used to create polygons.

Problem: About half of the .KAP files will also maintain the first lat/lon coordinate pair as the last lat/lon coordinate pair. (Very useful for closing polygons, see how PLY/1 and PLY/4 above are the same). For some reason some .KAP files do not have this. See where I'm going?

How would I ensure that the first coordinate pair is always recorded as the last coordinate pair in all the output CSV's?

Here's my code so far:

import os
import zipfile
import csv

currentPath = r"K:\BsbProd\BSBCHS\BSB_4_Release"

for zip in [i for i in os.listdir(currentPath) if i.lower().endswith('.zip')]:
zf = zipfile.ZipFile(os.path.join(currentPath, zip), 'r')
for each in [n for n in zf.namelist() if n.lower().endswith('.kap')]:
currentFile = zf.open(each).readlines()
writer = csv.writer(open(r"C:\Users\PalmerDa\Desktop\BSB\{}.csv".format(os.path.basename(each)), "wb"))
for row in currentFile:
if row.startswith('PLY'):
col1, col2 = row.split(",")[1:]
rows = float(col1), float(col2)
writer.writerow(rows)

Answer

When I had time to do it I came up with this solution to my own question:

import os
import zipfile
import csv
import glob

currentPath = r"K:\BsbProd\BSBCHS\BSB_4_Release"

for zip in glob.glob('{}/*.zip'.format(currentPath)):
    zf = zipfile.ZipFile(os.path.join(currentPath, zip), 'r')
    for each in [n for n in zf.namelist() if n.lower().endswith('.kap')]:
        currentFile = zf.open(each).readlines()
        writer = csv.writer(open(r"C:\Users\PalmerDa\Desktop\BSB2{}.csv".format(os.path.basename(each)), "wb"))
        plys = [r for r in currentFile if r.startswith('PLY')]
        for rr in plys:
            col1, col2 = rr.split(",")[1:]
            rows = float(col1), float(col2)
            writer.writerow(rows)
        if plys[0] != plys[-1]:
            writer.writerow((float(plys[0].split(",")[1]),float(plys[0].split(",")[2])))