# Small module to read columns from tabular oriented text
# files that consist entirely of integers and/or floats.
#
# Provides:
# readcol(file,colnum,flag) - Use this if you only need
# a few of columns or need memory
# efficiency
# readmat(file) - Use this if you need several
# columns
# readcolmat(table,colnum,flag)
def readcol(file,colnum,flag):
# Extracts a particular column from a file that contains
# a table of numerical values.
#
# Use this if you only need a small number columns
#
# Inputs:
# file = filename to read from
# = must be all numerical values in
# = rectangular table form
# column = column to extract
# flag == 1 => return column as integer
# flag == 2 => return column as float
#
# Outputs:
# x = column of data file
x = []
with open(file) as fnum:
for i in fnum:
linesplit = i.strip().split()
if flag == 1:
x.append(int(linesplit[0]))
elif flag == 2:
x.append(float(linesplit[1]))
return x
def readmat(file):
# Reads a table of numerical values from a text file.
#
# Use this along with readcolmat if you need to get several
# columns from the table
#
# Inputs:
# file = filename to read from
# = must be all numerical values in
# = rectangular table form
#
# Outputs:
# M = table values stored rowwise as a list of lists
# = returned as a double.
M = []
with open(file) as fnum:
for i in fnum:
x = []
linesplit = i.strip().split()
print(linesplit)
for j in range(len(linesplit)):
x.append(float(linesplit[j]))
M.append(x)
return M
def readcolmat(M,column,flag):
# Extracts a particular column from a table that has been
# stored rowwise as a list of lists.
#
# Inputs:
# M = table of values stored rowwise as list of lists
# column = column to extract
# flag == 1 => return column as integer
# flag == 2 => return column as float
#
# Outputs:
# x = column of M
x = []
n = len(M)
for i in range(0,n):
if flag == 1:
x.append(int(M[i][column-1]))
elif flag == 2:
x.append(float(M[i][column-1]))
return x
x = readcol('tabledata.dat',2,1)
M = readmat('tabledata.dat')
y = readcolmat(M,2,2)