[Tutor] Create a table by writing to a text file.
David Craig
dcdavemail at gmail.com
Wed Feb 22 14:14:44 CET 2012
Hi,
I have created a list of containing strings that represent distances
between many different points and would like to display the results in a
table.
I have been trying to write them to a text file but it is difficult to
organise them into rows and columns with appropriate spacing to make it
readable. I would like something like,
Stations Station1 Station2
Station1 0.0 33.57654
Station2 33.57654 0.0
but get,
Stations Station1 Station2
Station1 0.0 33.57654
Station2 33.57654 0.0
I've tried adding spaces but to some of the values (i.e. '0.0
') but this is very messy.
Is there a better way to do this?? My code is below.
Thanks
D
# Distance between stations
from dist import dist
import matplotlib.pyplot as plt
import numpy as np
# Guralp GPS decimal coordinates.
# station = [lat, lon, alt]
UFAN = [55.2333142, -7.6770179, 78.3]
UCRUI = [54.9846137, -8.3771698, 75.8]
UGLEN = [54.7064869, -8.7406732, 42.4]
UEASK = [54.2894659, -8.9583439, 9.1]
UACH = [53.8758499, -9.9621948, 22.0]
ULET = [53.5519317, -9.9413447, 70.4]
UHAG = [52.9393892, -9.4344939, 22.7]
ULOOP = [52.5809163, -9.8456417, 10.4]
UBALF = [52.1625237, -10.4099873, 74.3]
ULAMB = [51.7653115, -10.1531573, 13.5]
USHE = [51.5536226, -9.7907148, 115.3]
UGALL = [51.529665, -8.9529546, 33.4]
names = ['UFAN', 'UCRUI', 'UGLEN', 'UEASK', 'UACH', 'ULET', 'UHAG',
'ULOOP', 'UBALF', 'ULAMB', 'USHE', 'UGALL']
stations = [UFAN, UCRUI, UGLEN, UEASK, UACH, ULET, UHAG, ULOOP, UBALF,
ULAMB, USHE, UGALL]
distance = [[]]*len(stations)
for i in range(0,len(stations)):
#distance[i,0] = names[i]
temp = []
for j in range(0,len(stations)):
temp.append('
'+str(dist(stations[i][0],stations[i][1],stations[j][0],stations[j][1])))
distance[i] = temp
testFile = open('testFile.txt', 'a')
testFile.write('Stations ')
for i in range(0,len(stations)):
testFile.write(names[i]+' ')
testFile.write('\n')
for i in range(0,len(stations)):
testFile.write(names[i]+' ')
for j in range(0,len(stations)):
testFile.write(distance[i][j]+' ')
testFile.write('\n')
testFile.close()
More information about the Tutor
mailing list