I have a file containing information in three columns that have separated by different amount of spaces. How can i split the columns to the three separated columns? In order that I can calculate the average of the middle column.
Example from the data file.
0 41 216
10 42 214
20 43 215
30 39 222
40 34 222
50 35 215
60 42 218
70 37 213
80 41 216
90 43 222
100 33 220
My code
def main ():
total = 0.0
n = 0
aveg = 0.0
try:
inputfile = open("inputfile.txt", "r")
for line in inputfile:
line = line.rstrip()
if line[0] != '#' and line[0] != '@':
line = line.strip()
data = line.split(" ")
print(data[1])
bonds = data[1]
float(bonds)
total = total + bonds
n = n + 1
inputfile.close
except OSError:
print("OSError")
aveg = total/n
print("Average:", aveg)
main()
pandas?pandas.read_csv('inputfile.txt', sep='\s+')will take care of everything you want :)" "and not"\t"?line.split()see my answer