Ying Zu zuy...@gmail.com wrote:
How to read ansic file into a pre-defined class?
This is not an ansic file. It's just a plain old data file.
I have a series of files written in the following format,
2 # number of classes
100 # number of items for the first class object
0 foo
1 foo
...
99 foo
150 # number of items for the second class object
0 bar
1 bar
...
149 bar
ultimately I want to read the file to two *structs* (sorry for my C
jargon, just started playing with Python), with attributes
number_of_items and data_array.
I wrote a simply code to read and split each line into a list, then
try to tell the meaning of each line by the number of elements of
each line list and the its position in the file. But it is
definitely not the way Python should be used.
You don't really need to count the number of elements. The file tells you
how many of each to expect. This works:
numclasses = int(f.next().strip())
classlist = []
for i in range(numclasses):
numitems = int(f.next().strip())
classlist.append(
[f.next().strip().split() for j in range(numitems)]
)
Then len(classlist) tells you how many classes. len(classlist[0]) tells
you how many items in the first class.
--
Tim Roberts, t...@probo.com
Providenza Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list