-1

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)

Moose
  • 5
  • 4
  • What happens if you write `repr(element)` instead of `str(element)`? – khelwood Dec 19 '21 at 01:15
  • That got rid of it putting different stuff in the file but I still have the extra line. Thanks for the help with the first part! – Moose Dec 19 '21 at 01:23

1 Answers1

0

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.

khelwood
  • 55,782
  • 14
  • 81
  • 108