text file based information access by field name and number

TrustyTony 0 Tallied Votes 1K Views Share

The code from my answer to thread: http://www.daniweb.com/forums/thread292949.html

Any field names with any same separator separating the values. This is straight text file reading routine, see the original thread for csv module based code.

sample.dat:

id; name; email; homeaddress
123; gishi; gishi@mymail.com; 456 happy st.
345; tony; tony.veijalainen@somewhere.com; Espoo Finland
# text based data input with data accessible
# with named fields or indexing
from __future__ import print_function ## Python 3 style printing
from collections import namedtuple
import string

filein = open("sample.dat")

datadict = {}

headerline = filein.readline().lower() ## lowercase field names Python style
## first non-letter and non-number is taken to be the separator
separator = headerline.strip(string.lowercase + string.digits)[0]
print("Separator is '%s'" % separator)

headerline = [field.strip() for field in headerline.split(separator)]
Dataline = namedtuple('Dataline',headerline)
print ('Fields are:',Dataline._fields,'\n')

for data in filein:
    data = [f.strip() for f in data.split(separator)]
    d = Dataline(*data)
    datadict[d.id] = d ## do hash of id values for fast lookup (key field)

## examples based on sample.dat file example
key = '123'
print('Email of record with key %s by field name is: %s' %
      (key, datadict[key].email))

## by number
print('Address of record with key %s by field number is: %s' %
      (key ,datadict[key][3]))

## print the dictionary in separate lines for clarity
for key,value in  datadict.items():
    print('%s: %s' % (key, value))

input('Ready') ## let the output be seen when run directly

""" Output:
Separator is ';'
Fields are: ('id', 'name', 'email', 'homeaddress') 

Email of record with key 123 by field name is: gishi@mymail.com
Address of record with key 123 by field number is: 456 happy st.
345: Dataline(id='345', name='tony', email='tony.veijalainen@somewhere.com', homeaddress='Espoo Finland')
123: Dataline(id='123', name='gishi', email='gishi@mymail.com', homeaddress='456 happy st.')
Ready
"""
TrustyTony 888 pyMod Team Colleague Featured Poster
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.