Back to SDS/2 Parametric Scripts
## ReadFileData.py version 1.01
## Copyright (c)
2007 Bruce Vaughan, BV Detailing & Design, Inc.
## All rights
reserved.
## NOT FOR
########################################################################################
"""
Class definition -
Upon instantiation, the data file is read and a dictionary is created
containing data.
The default
delimiter is '\t' (tab).
Sample data file,
tab delimited:
conn spa1 spa2 length height s1 s2 spaces
#########################################################
# These
are comment lines. The first line above contains the
# variable
names of column labels. They must be valid names
# if
used for variable names.
# This
class supports floats, integers, and strings.
# A string written
in feet'-inch xx/xx format will be
# converted to a
float.
# The
script will attempt to convert to int and then float
# and
then from FI16ths to float.
# If
the conversions fail, the original string is returned.
# A float must have
a '.' and at least one decimal place.
# A
string in FI16th format must have ' or '- after feet.
# The
first column contains the dictionary keys.
#########################################################
C1 3.0 4.0 7'-2 10.2 Bill Joe 4
C2 4.0 5.0 1'6 3/8 11.6 Tom Jerry 6
C3 12.0 2.2 2-9 3/4 22.8 Rick Jim 10
Version History:
Version 1.01 (
"""
from param import
Warning
import os
import sys
if 'C:\\
sys.path.append('C:\\
from macrolib.fifDim
import dim__
data_file = os.path.join('C:\\',
'
class ReadFileData(object):
def __init__(self,
fn, delim='\t'):
try:
f = open(fn,
'r')
"""
The first line is a header line or
line of variable names.
The line is split on delimiter ('delim').
The first line is stored in self.labels.
The first item in self.labels coincides with self.dict.keys()
and should
be skipped when appying dictionary values to
variable
names. See example in test function below.
"""
self.labels
= f.readline().strip().split(delim)
dataList = []
for line
in f:
# Skip lines that start with '#'
if not
line.startswith('#'):
# Split on delimiter
dataList.append(line.strip().split(delim))
f.close()
self.data
= dataList
self.dict
= {}
for i in range(len(dataList)):
# convert
file data to int, float, dim__ where possible
for j
in range(1, len(dataList[i])):
dataList[i][j]
= self.convertType(dataList[i][j].strip())
# apply to dictionary
self.dict[dataList[i][0]] = dataList[i][1:]
except:
Warning("Data
file was not found or\n Data file was invalid or\nAn
error occured in '__init__'")
self.labels
= None
self.data
= None
self.dict
= None
def __iter__(self):
for key in self.dict.keys():
yield key
def __repr__(self):
return
'<data file list object, ReadFileData class>'
def convertType(self, s):
for func in (int, float, dim__):
try:
n = func(s)
return
n
except:
pass
return s
###################################
def test_script(f):
# Create a variable list if the header line
is not suitable for variable names
# variable_list =
['conn', 'spa1', 'spa2', 'length', 'height', 's1',
's2', 'spaces']
b = ReadFileData(f)
if b.dict != None:
connList
= []
for key in b:
connList.append(key)
connList.sort()
# For
execution in Pythonwin
"""
print 'The
connection types are:',
for i in connList:
print i, "",
print
print
connMk
= raw_input("Enter connection")
print_doc =
"No"
"""
# For
execution in
from param import Dialog
## DIALOG
dlg1 = Dialog(
"Connection Information")
dlg1.menu("print_doc", ("Yes", "No"),
"No", "Print documentation")
dlg1.menu('connMk', connList, connList[0], "Select connection")
dd1 = dlg1.done()
# Update the local namespace
for key, value
in dd1.items():
exec
"%s = %s" % (key, repr(value)) in None
# Assign data values to variable names
from b.labels for selected connection.
# In this case, the 1st column label is
the dictionary key, so it is skipped.
print
"Connection = %s" % (connMk)
for i, label in enumerate(b.labels[1:]):
exec "%s =
%s" % (label, repr(b.dict[connMk][i])) in None
print
"%s = %s" % (label, eval(label))
print
for key in b:
print 'Key
= %s' % (key)
print '%s
= %s' % (key, b.dict[key])
if print_doc == "Yes":
print
__doc__
## End test_script()
if __name__ == '__main__':
try:
test_script(data_file)
finally:
del ReadFileData
"""
Output in
Connection = C1
spa1 = 3.0
spa2 = 4.0
length = 82.0
height = 10.2
s1 = Bill
s2 = Joe
spaces = 4
Key = C3
C3 = [12.0,
2.2000000000000002, '2-9 3/4', 22.800000000000001, 'Rick', 'Jim', 10]
Key = C2
C2 = [4.0, 5.0,
18.375, 11.6, 'Tom', 'Jerry', 6]
Key = C1
C1 = [3.0, 4.0,
82.0, 10.199999999999999, 'Bill', 'Joe', 4]
"""