Newbie DATA STRUCTURES Question.
Huaiyu Zhu
hzhu at localhost.localdomain
Mon Jul 31 00:01:52 EDT 2000
On Sat, 29 Jul 2000 02:57:03 GMT, gbp <gpepice1 at nycap.rr.com> wrote:
>
>I have experience with Perl but non with Python.
>
>I need to write a script to read a large text file into a structured
>format.
>
>In Perl one can create a list of records using something like pointers.
>So really you have a list of pointers-- each one pointing to an
>anonymous record. Each record is some data from a line in the file.
>
Others have given more general answers, but I think you might have this
specific question in mind: you have a file of form
11 12 13
21 22 23
...
and you want to get a list of dictionaries (ie an array of hashes in Perl)
result = [{'a':11, 'b':12, 'c':13},
{'a':21, 'b':22, 'c':23},
...
]
You can do it as the following (not tested)
file = open(filename) # or file = sys.stdin
names = ['a','b','c']
result = []
for line in file.readlines():
fields = string.split(line) # or use re to extract the fields
record = {}
for name, field in map(None, names, fields):
record[name] = field
result.append(record)
Hope this helps.
Huaiyu
More information about the Python-list
mailing list