Home > OS >  Python CSV read then write variables to template
Python CSV read then write variables to template

Time:11-12

I am struggling to create the correct python script to read a CSV file then input the variables from the CSV file into a template. Here is an example of what I am trying to achieve:

CSV File Input:

LAT,LONG
-
80.0,30.0
-
82.0,31.0
-
85.3,32.7
-

So on and on with thousands of various lat/long points....

Template: <Object lat="", long="">

With the end result being one .txt file that looks like:

<Object lat="80.0", long="30.0"> <Object lat="82.0", long="31.0"> <Object lat="85.3", long="32.7">

I have thousand of lat/long points within a CSV file that I am wanting to write into the above template resulting in one .txt file. I am new to python, but still trying to learn. Any help would be greatly appreciated.

Thanks!

CodePudding user response:

import csv

csv_file_path = 'coordinates.csv'
template = '<Object lat="{}", long="{}">'
output = ''

with open(csv_file_path, 'r') as csv_file:
    reader = csv.DictReader(csv_file)
    for row in reader:
        output  = template.format(row['LAT'], row['LONG'])

with open('output.txt', 'w') as txt_file:
    txt_file.write(output)
  • Related