简单的CSV转换为KML文件的Python程序
1、创建KML线文件模板库
LineKml = “”“<?xml version="1.0" encoding="UTF-8"?>
1
1
absolute
”“”
strlist = LineKml.split(“\n”)
2、读取CSV文件,遍历选择目录
for root, dirs, files in os.walk(file_path, topdown=False):
for source_file in files: # 遍历目录文件
if source_file.endswith(‘.csv’): # 遍历csv文件
tmp = os.path.join(root, source_file)
aim_file = tmp[:-3] + ‘kml’
write_data(aim_file, tmp)
aim_num = aim_num + 1
status[‘text’] = status[‘text’] + ‘已转换’ + str(aim_num) + ‘个’ # 修改完更新状态
3、将CSV坐标写入到KML文件中
def write_data(aim_file, file_sourse): # 传入目标文件与待读取csv文件
global Longitude, Latitude, Altitude, StartLine
with open(aim_file, “w”) as file: # 创建目标kml文件
for i in strlist:
file.write(i + “\n”)
if i.endswith(“”):
with open(file_sourse, ‘r’, encoding=‘utf-8’, newline=‘’) as csv_file: # 读取csv文件
data = csv.reader(csv_file)
line_idx = 0
for csv_row in data:
if line_idx > StartLine:
# tmp = csv_row[ord(Longitude)-ord(‘A’)]+‘,’+csv_row[ord(Latitude)-ord(‘A’)]+‘,’+csv_row[ord(Altitude)-ord(‘A’)]#
tmp = csv_row[Longitude-1] + ‘,’ + csv_row[Latitude-1] + ‘,’ + csv_row[Altitude-1]
# print(tmp)
file.write(“\t\t\t” + tmp) # 写入数据
file.write(‘\n’)
line_idx += 1