1

I would like to write a new row after reading each file. This is from KML to CSV.

At the of the day: - Each file should write the values into columns - New row for each kml file

from bs4 import BeautifulSoup
import csv
import os
import glob

def process_coordinate_string(str):

    comma_split = str.split(',')
    return [comma_split[1].strip(), comma_split[0].strip()]


def main():
    """
    Open the KML. Read the KML. Open a CSV file. Process a coordinate string to be a CSV row.
    """

    files = []
    for i in os.listdir('<dir>'):
        if i.endswith('.kml'):
            with open(i, 'r') as f:
                s = BeautifulSoup(f, 'xml')
                with open('out.csv', 'w') as csvfile:
                    writer = csv.writer(csvfile,lineterminator='')
                    for names in s.find_all('name',):
                        writer.writerow(names)

                    for coords in s.find_all('coordinates'):
                        writer.writerow(process_coordinate_string(coords.string))



main()
ywologist
  • 23
  • 4

1 Answers1

1

use

with open('out.csv', 'a') as csvfile:

instead of

with open('out.csv', 'w') as csvfile:



from bs4 import BeautifulSoup
import csv
import os
import glob

def process_coordinate_string(str):

    comma_split = str.split(',')
    return [comma_split[1].strip(), comma_split[0].strip()]


def main():
    """
    Open the KML. Read the KML. Open a CSV file. Process a coordinate string to be a CSV row.
    """

    files = []
    for i in os.listdir('.'):
        if i.endswith('.kml'):
            with open(i, 'r') as f:
                s = BeautifulSoup(f, 'xml')
                with open('out.csv', 'a',) as csvfile:
                    writer = csv.writer(csvfile,lineterminator='')
                    for names in s.find_all('name',):
                        writer.writerow(names)

                    for coords in s.find_all('coordinates'):
                        writer.writerow(process_coordinate_string(coords.string))

                        print(dir(writer))
                    writer.writerow("\n")



main()
ArunJose
  • 1,999
  • 1
  • 10
  • 33