hi im using python on jupyter notebook and i want to know how to add the x and y coordinates to a list from a text file containing coordinates into list.
The list is called citylist=[] filename is cities8 enter image description here
how do i append these coordinates into a list. Thank you so much for your time guys.
CodePudding user response:
Assuming the data is separated by white spaces this can be done as follows:
with open('FILE_NAME_GOES_HERE', 'r') as f:
data = f.readlines()
x_coordinates = []
y_coordinates = []
for line in data:
_, x, y = line.split()
x_coordinates.append(int(x))
y_coordinates.append(int(y))
You can get the idea from here and make your own list in whatever format you want
CodePudding user response:
First of all you have to read that file and split it using newline
citylist=[]
cities = open("cities8.txt", "r")
coordinates = cities.read().split("\n") # this will read and split file
cities.close() # close the file
for city in coordinates:
citylist.append(city.split(" ")[1:])
Now to print coordinates you can loop through the list
for i in citylist:
print(f"X:{i[0]}, Y:i[1]")