Hi

I have a file, let's call it file.xml which contains information on the 1st and 3rd line (xml header and footer).

What I would like to do is always write to the 2nd line so that the header and footer remain in the correct place.

This is a gps python script so it's forever adding data to the file in a loop

Can anyone give me a few pointers on how this can be done?

many thanks

Recommended Answers

All 2 Replies

This is my current code, (doesn't work)

filename = "gps.xml"
						file = open(filename, 'r')
						filedata = file.read()
						lines = file.readlines()
						file.close()
						file = open(filename, 'w')
						now = strftime("%Y-%m-%d %H:%M:%S")
						kml = (
							'<Position>\n'
							'	<Latitude>%s</Latitude>\n'
							'	<Longitude>%s</Longitude>\n'
							'	<Altitude>%s</Altitude>\n'
							'	<Time>%s</Time>\n'
							'</Position>'
							) % (self.latitude, self.longitude, self.altitude, now)
						lines[2] = "%s\n" %(kml)
						file.writelines(lines)
						file.close

If the footer is not too long, you could store it and write it after your data. For example

f = open("gps.xml", "r+w")
f.seek(-sizeoffooter, 2) # go to the beginning of the footer
footer = f.read() # store the footer
f.seek(-sizeoffooter, 2) # go to the beginning of the footer
f.write(newdata)  # write your data, overwriting the footer
f.write(footer) # rewrite the footer after your data
f.close()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.