f.write to kml files - python

So, I've been tasked with writing kml files from phython, without using simplekml. I going wrong in the code... can anyone please identify the mistake?
#Input the file name."XYpoints1_wgs84"
fname = input("Enter file name WITHOUT extension: ")
data = csv.reader(open(fname + '.csv'), delimiter = ',')
#Skip the 1st header row.
#data.next()
#Open the file to be written.
f = open('Buffered_kml.kml', 'w')
#Writing the kml file.
f.write("<?xml version='1.0' encoding='UTF-8'?>\n")
f.write("<kml xmlns='http://earth.google.com/kml/2.1'>\n")
f.write(" <name>" + fname + '.kml' +"</name>\n")
f.write(" <Polygon> <outerBoundaryIs> <LinearRing>\n")
f.write(" <coordinates>\n" )
next(data)
for row in data:
f.write(str((row[1])) + "," + (str(row[2]))+"\n")
f.write(" </coordinates>\n" )
f.write(" </LinearRing> </outerBoundaryIs> </Polygon> \n")
f.write("</kml>\n")
print ("File Created. ")
print ("Press ENTER to exit. ")
input()
f.close()
It does produce kml file but without the coordinate end tag. Why is this happening?

Related

re module doesn't save the whole text into txt file

Here's the code:
import re
file_name = input("Please input txt directory for your file: ")
#file_name2 = input("Please input txt directory for your file: ")
with open(file_name, 'r') as lol:
for txt_file in lol:
x = re.sub(r"[^a-zA-Z0-9]+", ' ', txt_file)
print(x)
It's going to print text without special characters. However, I need to save the printed text to a file. When I do so, it saves only the single line from txt file instead of the whole txt.
import re
file_name = input("Please input txt directory for your file: ")
#file_name2 = input("Please input txt directory for your file: ")
with open(file_name, 'r') as lol:
for txt_file in lol:
x = re.sub(r"[^a-zA-Z0-9]+", ' ', txt_file)
with open(file_name2, 'w') as p:
p.write(x)
p.close()
Your codes aren't the same; you're not writing within the loop anymore.
Did you know you can open multiple files at once?
with open(file_name, 'r') as lol, open('output.txt', 'w') as f_out:
for txt_file in lol:
x = re.sub(r"[^a-zA-Z0-9]+", ' ', txt_file)
f_out.write(x)
f_out.write('\n')

Write input file with any number of lines to tab-delimited output [duplicate]

This question already has answers here:
Why can't I call read() twice on an open file?
(7 answers)
Closed last month.
I'm trying to write a script that will take an input file with an unknown number of columns separated by commas and create a new file (name specified by user) where columns are separated by tabs.
The test input file I'm working with looks like this:
Data 1,35,42,7.34,yellow,male
Data 2,41,46,8.45,red,female
Here is the code I have so far:
# Read input file
infile = open("input_file.txt", "r")
line_count = 0
# Read as a collection, removing end line character
for line in infile:
print(line, end = "")
print("The input file contains", line_count, "lines.")
# Request user input for output file name
filename = input("Enter a name for the output file: ")
# Prompt for file name if entry is blank or only a space
while filename.isspace() or len(filename) == 0:
filename = input("Whoops, try again. Enter a name for the output file: ")
# Complete filename creation
filename = filename + ".txt"
filename = filename.strip()
# Write output as tab-delim file
for line in infile:
outfile = open(filename, "w")
outfile.write(line,"\t")
outfile.close()
print("Success, the file", filename, "has been written.")
# Close input file
infile.close()
The part that writes the output isn't working - it doesn't produce an error, but the output is blank.
You can split the lines by commas and write while adding tab(\t) chars :
with open('input_file.txt','r') as f_in, open('output_file.txt', 'w') as f_out:
for line in f_in:
s = line.strip().split(',')
for i in s:
f_out.write(i+'\t')
f_out.write('\n')
or briefly as #martineau suggested :
with open('input.txt','r') as f_in, open('output.txt', 'w') as f_out:
for line in f_in:
s = line.strip().split(',')
f_out.write('\t'.join(s) + '\n')
You may use pandas:
import pandas as pd
df = pd.read_csv("input_file.txt", sep=',',header=None)
print("The input file contains", df.shape[0], "lines.")
filename = input("Enter a name for the output file: ").strip()
# Prompt for file name if entry is blank or only a space
while filename.isspace() or len(filename) == 0:
filename = input("Whoops, try again. Enter a name for the output file: ")
#Saving to csv with | separator
df.to_csv(f'{filename}.txt', sep="\t", header=None, index=None)
print("Success, the file", filename, "has been written.")

Python reading a text file but prints nothing

I tried different methods of printing out the text file. But it doesn't print anything.
There is code in the text file for sure, and I am spelling it right.
Why doesn't it print anything from the text file?
f = open("quotes.txt", "r")
print("Name of the file:", f.name)
line = f.readline()
print("Read Line: %s" % line)
data = f.read()
print("Data: ", data)
f.close()
This is what it prints:
Name of the file: quotes.txt
Read Line:
Data:

Trying to make a KML file in Python

I'm still very new to python, i am trying to export the locations on a list (List2) into a kml file which will then display the results on google maps. I have no idea really what i am doing and atm all i am getting is a syntax error around every ,", symbol. Can someone help me with this please.
KMLFile = open("KML.txt", "w")
f.write("<KML_File>\n")
f.write("<Document>\n")
for line in List2:
f.write(" <Placemark>")
f.write(" <decription>" + str(row[0]) + "</description>")
f.write(" <Point>")
f.write(" <coordinates>" + str(row[2]) + str(row[1])"</coordinates>")
f.write(" </Point>")
f.write(" </Placemark>")
f.write("</Document>\n")
f.write("</kml>\n")
KMLFile = close()
Hard-coding XML output to create a KML file in a series of print statements is error-prone and hard to maintain. Rather use a Python KML library such as simplekml or pyKML to generate the KML. The simplekml API simplifies writing KML and produces valid KML with code that is cleaner and easier to understand.
import simplekml
# list2 = ...some assignment with list of point data elements
kml = simplekml.Kml()
for row in list2:
kml.newpoint(description=row[0],
coords=[(row[2], row[1])]) # lon, lat, optional height
# save KML to a file
kml.save("test.kml")
Using this test input for a single point:
list2 = [ [ 'description', 51.500152, -0.126236 ] ] # description, lat, lon
The KML output would be this:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
<Document id="feat_1">
<Placemark id="feat_2">
<description>description</description>
<Point id="geom_0">
<coordinates>-0.126236,51.500152,0.0</coordinates>
</Point>
</Placemark>
</Document>
</kml>
In brief:
You should change KMLFile to f or vice versa.
You should call the close() method like this : f.close().
Your corrected code:
f = open("KML.txt", "w")
f.write("<KML_File>\n")
f.write("<Document>\n")
for line in List2:
f.write("\t<Placemark>")
f.write("\t\t<decription>" + str(row[0]) + "</description>")
f.write("\t\t<Point>")
f.write("\t\t\t<coordinates>" + str(row[2]) + str(row[1]) + "</coordinates>")
f.write("\t\t</Point>")
f.write("\t</Placemark>")
f.write("</Document>\n")
f.write("</kml>\n")
f.close()
In addition, if you do not want to write the f.close() line and let python manage the file closure:
with open("KML.txt", "w") as f:
f.write("<KML_File>\n")
f.write("<Document>\n")
for line in List2:
f.write("\t<Placemark>")
f.write("\t\t<decription>" + str(row[0]) + "</description>")
f.write("\t\t<Point>")
f.write("\t\t\t<coordinates>" + str(row[2]) + str(row[1]) + "</coordinates>")
f.write("\t\t</Point>")
f.write("\t</Placemark>")
f.write("</Document>\n")
f.write("</kml>\n")
Eventually, if you do not want to have many + into your f.write() lines, you can also opt for the format() method:
f.write("\t\t\t<coordinates>{}{}/coordinates>".format(row[2], row[1]))
In your code you haven't defined the variable f which should reference the file-object you want to write to. You could either do
f = open("KML.txt", "w")
f.write("<KML_File>\n")
...
f.close()
or better:
with open("KML.txt", "w") as f:
f.write("<KML_File>\n")
...
which makes sure to always close the file even if some code in between fails.
For writing XML-files you might want to take a look at the Python xml-package.
import geopandas as gpd
polys = gpd.GeoDataFrame(df)
polys.to_file(r'../docs/database.kml', driver = 'KML')
df should contain description, geometry, name.

Create kml from csv in Python

I am new to Python. I am working on gps files. I need to convert a CSV file having all the gps data to kml file. Below is the code in python I am using :
import csv
#Input the file name.
fname = raw_input("Enter file name WITHOUT extension: ")
data = csv.reader(open(fname + '.csv'), delimiter = ',')
#Skip the 1st header row.
data.next()
#Open the file to be written.
f = open('csv2kml.kml', 'w')
#Writing the kml file.
f.write("<?xml version='1.0' encoding='UTF-8'?>\n")
f.write("<kml xmlns='http://earth.google.com/kml/2.1'>\n")
f.write("<Document>\n")
f.write(" <name>" + fname + '.kml' +"</name>\n")
for row in data:
f.write(" <Placemark>\n")
f.write(" <name>" + str(row[1]) + "</name>\n")
f.write(" <description>" + str(row[0]) + "</description>\n")
f.write(" <Point>\n")
f.write(" <coordinates>" + str(row[3]) + "," + str(row[2]) + "," + str(row[4]) + "</coordinates>\n")
f.write(" </Point>\n")
f.write(" </Placemark>\n")
f.write("</Document>\n")
f.write("</kml>\n")
print "File Created. "
print "Press ENTER to exit. "
raw_input()
The csv file I am using is available here : dip12Sep11newEdited.csv
The kml file generated is available here : csv2kml.kml
But the kml file is not getting created correctly. Apparently after some rows in the csv the code is not able to generate more Placemarks. Its not able to iterate. You can see that by scrolling to the last part of the kml file generated.
Can anyone help me finding out the error in the code, because for some smaller csv files it worked correctly and created kml files fully.
Thanks.
You didn't answer the query above, but my guess is that the error is that you're not closing your output file (which would flush your output).
f.close()
use etree to create your file
http://docs.python.org/library/xml.etree.elementtree.html
It's included with Python and protects you from generating broken XML. (eg. because fname contained &, which has special meaning in XML.)
This code is well written thank you for the post. I got it to work by putting my CSV in the same directory as the .py code.
I made a few edits to bring it to py 3.3
import csv
#Input the file name."JoeDupes3_forearth"
fname = input("Enter file name WITHOUT extension: ")
data = csv.reader(open(fname + '.csv'), delimiter = ',')
#Skip the 1st header row.
#data.next()
#Open the file to be written.
f = open('csv2kml.kml', 'w')
#Writing the kml file.
f.write("<?xml version='1.0' encoding='UTF-8'?>\n")
f.write("<kml xmlns='http://earth.google.com/kml/2.1'>\n")
f.write("<Document>\n")
f.write(" <name>" + fname + '.kml' +"</name>\n")
for row in data:
f.write(" <Placemark>\n")
f.write(" <name>" + str(row[1]) + "</name>\n")
f.write(" <description>" + str(row[3]) + "</description>\n")
f.write(" <Point>\n")
f.write(" <coordinates>" + str(row[10]) + "," + str(row[11]) + "," + str() + "</coordinates>\n")
f.write(" </Point>\n")
f.write(" </Placemark>\n")
f.write("</Document>\n")
f.write("</kml>\n")
print ("File Created. ")
print ("Press ENTER to exit. ")
input()
f.close()
Hope it helps if you are trying to convert your data.
One answer mentions the "etree", one advantage that you do not have to hardcode the xml format:
Below one of my examples, of course you have to adjust it to your case, but you may get the principle idea of how etree works:
to get something like this
<OGRVRTDataSource>
<OGRVRTLayer name="GW1AM2_201301010834_032D_L1SGRTBR_1110110_channel89H">
<SrcDataSource>G:\AMSR\GW1AM2_201301010834_032D_L1SGRTBR_1110110_channel89H.csv</SrcDataSource>
<GeometryType>wkbPoint</GeometryType>
<GeometryField encoding="PointFromColumns" x="lon" y="lat" z="brightness" />
</OGRVRTLayer>
</OGRVRTDataSource>
you can use this code:
import xml.etree.cElementTree as ET
[....]
root = ET.Element("OGRVRTDataSource")
OGRVRTLayer  = ET.SubElement(root, "OGRVRTLayer")
OGRVRTLayer.set("name", AMSRcsv_shortname)
SrcDataSource = ET.SubElement(OGRVRTLayer, "SrcDataSource")
SrcDataSource.text = AMSRcsv
GeometryType = ET.SubElement(OGRVRTLayer, "GeometryType")
GeometryType.text = "wkbPoint"
GeometryField = ET.SubElement(OGRVRTLayer,"GeometryField")
GeometryField.set("encoding", "PointFromColumns")
GeometryField.set("x", "lon")
GeometryField.set("y", "lat")
GeometryField.set("z", "brightness")
tree = ET.ElementTree(root)
tree.write(AMSRcsv_vrt)
also some more info here
The simplekml package works very well, and makes easy work of such things.
To install on Ubuntu, download the latest version and run the following from the directory containing the archive contents.
sudo python setup.py install
There are also some tutorials to get you started.
Just use simplekml library to create kml easily.. instead of writing the kml data.. I achieved it directly by using simplekml.
import simplekml
Read the documentation of simplekml
with open(arguments+'.csv', 'r') as f:
datam = [(str(line['GPSPosLongitude']), str(line['GPSPosLatitude'])) for line in csv.DictReader(f)]
kml = simplekml.Kml()
linestring = kml.newlinestring(name='linename')
linestring.coords = datam
linestring.altitudemode = simplekml.AltitudeMode.relativetoground
linestring.style.linestyle.color = simplekml.Color.lime
linestring.style.linestyle.width = 2
linestring.extrude = 1
kml.save('file.kml')
kml.savekmz('file.kmz', format=False)
kml2geojson.main.convert('file.kml', '')

Categories