Source (Text):
def _parseFile(file):
""" responsible for parsing the file and returning the datastructure """
parsed={}
columns=[]
f=open(file, 'r')
lines=f.readlines()
for column in lines[0].split(','):
column=column.strip()
columns.append(column)
parsed[column]=()
for line in lines[1:]:
data=line.strip().split(',')
for x in range(0, len(columns)):
column_name=columns[x]
values=parsed[column_name]
parsed[column_name]=values+(data[x], )
f.close()
return parsed
def _queryCSVMapping(map, field, value):
""" return the position (of the sequence of dat) inside the value of the mapping """
values=map[field]
results=()
for x in range(0, len(values)):
if value==values[x]:
results=results+(x,)
return results
def _getDataFromLineNumbers(file, line_nums):
data=()
f=open(file, 'r')
contents=f.readlines()
for line_num in line_nums:
data=data+(contents[line_num+1],)
f.close()
return data
def csv_query(file, field, value):
csv_mapping=_parseFile(file)
line_number=_queryCSVMapping(csv_mapping, field, value)
lines=_getDataFromLineNumbers(file, line_number)
return lines
John Smith,111-1111,123456789
John Smith,222-2222,123456789
Betty Lee,333-3333,234567890
Joe Anderson,444-4444,345678901
f='e:\\zope25b1\\extensions\\data.csv'
data=context.queryCSVFile(f, 'phone', '222-2222')
return data
John Smith,222-2222,123456789
<dtml-in "queryCSVFile('e:\\zope25b1\\extensions\\data.csv', 'name', 'John Smith')">
<dtml-var sequence-item> <br />
</dtml-in>
John Smith,111-1111,123456789 <br/>
John Smith,222-2222,123456789 <br/>
|
Explanation:
_parseFile opens a file, f reads the first line (lines[0]) into
a sequence called columns. then it iterates over the rest of the lines
putting them into the mapping {}, parsed.
{'name':('John Smith','John Smith','Betty Lee', 'Joe Anderson'),
'ssn':(other stuff),
'phone': (phone sequence) }
_queryCSVMapping takes the field and value and queries the parsed
mapping and returns the sequence number it found in the values. it returns
the column number found in the sequence.
_getdataFromLineNumbers opens the line and returns that line from the
csv file.
|