Search code examples
pythongeolocationgeopy

Different data is being added to a file than is being printed in the console


I have been writing a program to get all the coordinates within a ten mile radius of any given point and when the distance data is printed its output is different from the data in the file. Not only this but it creates a blank line at the end of the file. What should I do?

import geopy.distance
distance_data = open("Distance from start.txt", "w")
distance_data.truncate()
distance_data_to_add = []
for i in range (360):
    bearing = i
    lat = 51.8983
    long = 177.1822667
    for i in range (10):
        distance = i
        new_lat_long = 
        geopy.distance.distance(miles=distance).destination((lat, long), bearing=bearing)
    distance_data_to_add.append(new_lat_long)
for element in distance_data_to_add:
    distance_data.write(str(element) + "\n")
print(distance_data_to_add)

An example line from the file is:
51 56m 30.0669s N, 177 10m 51.749s E

An example of the printed info in the console is:
Point(51.94168524994642, 177.1810413957121, 0.0)


Solution

  • The reason the objects look different in a list is because that is the repr version of them, not the str version. So write repr(element) to the file instead of str(element).

    The reason there is a newline at the end of the file is because you write \n after every element.

    Replace this:

    for element in distance_data_to_add:
        distance_data.write(str(element) + "\n")
    

    with this:

    distance_data.write('\n'.join(map(repr, distance_to_add)))
    

    That will write the repr of each object, with a newline between each one (but not at the end).

    And don't forget distance_data.close() after you finish writing your file.