Python CSV 读取然后将变量写入模板
Python CSV read then write variables to template
我正在努力创建正确的 python 脚本来读取 CSV 文件,然后将 CSV 文件中的变量输入到模板中。这是我要实现的目标的示例:
CSV 文件输入:
LAT,LONG
-
80.0,30.0
-
82.0,31.0
-
85.3,32.7
-
等等,数以千计的各种 lat/long 点....
模板:
最终结果是一个 .txt 文件,如下所示:
我在一个 CSV 文件中有上千个 lat/long 点,我想将这些点写入上述模板,生成一个 .txt 文件。我是 python 的新手,但仍在努力学习。任何帮助将不胜感激。
谢谢!
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)
我正在努力创建正确的 python 脚本来读取 CSV 文件,然后将 CSV 文件中的变量输入到模板中。这是我要实现的目标的示例:
CSV 文件输入:
LAT,LONG
-
80.0,30.0
-
82.0,31.0
-
85.3,32.7
-
等等,数以千计的各种 lat/long 点....
模板:
最终结果是一个 .txt 文件,如下所示:
我在一个 CSV 文件中有上千个 lat/long 点,我想将这些点写入上述模板,生成一个 .txt 文件。我是 python 的新手,但仍在努力学习。任何帮助将不胜感激。
谢谢!
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)