Newbie DATA STRUCTURES Question.
Kirby Urner
urner at alumni.princeton.edu
Sat Jul 29 00:53:05 EDT 2000
gbp <gpepice1 at nycap.rr.com> wrote:
>
>Hi all,
>
>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.
Not sure if this is what you mean, but suppose you create
a text file .\ocn\data.txt:
this is record A
this is record B
this is record C
then you can read it into a list like so:
>>> myfile = open(r".\ocn\data.txt", 'r') # see note
>>> listrecs = myfile.readlines()
>>> listrecs
['this is record A\012', 'this is record B\012', 'this is record C\012']
>>> myfile.close()
\012 must be unicode for newline.
>>> unicode('\n')
u'\012'
Yep.
Once you have 'listrecs' with all your records, you can
do stuff like:
for rec in listrecs:
dostuff(rec)
or map(dostuff,listrecs)
i.e. you're stepping through the records one record at a time.
Kirby
Note:
in
>>> myfile = open(r".\ocn\data.txt", 'r')
the leading r, in front of the first quoted string, just
means you don't have to escape the backslashes. You could
also go:
>>> myfile = open(".\\ocn\\data.txt", 'r')
More information about the Python-list
mailing list