[Tutor] Nested loop of I/O tasks
kent37 at tds.net
Wed Nov 25 12:25:22 CET 2009
On Tue, Nov 24, 2009 at 5:42 PM, Bo Li <boli1285 at gmail.com> wrote:
> Dear Python
> I am new to Python and having questions about its usage. Currently I have
> to read two .csv files INCT and INMRI which are similar to this
> My job is to match the name on the two files and combine the first three
> attributes together. So far I tried to read two files. But when I tried to
> match the pattern using nested loop, but Python stops me after 1 iteration.
That is because you can only iterate an open file once. You iterate INMRI in
a loop; only the first iteration will give any rows.
A simple fix is to read INMRI into a list using readlines(). Lists can be
> Here is what I got so far.
> INCT = open(' *.csv')
> INMRI = open(' *.csv')
INMRI = open(' *.csv').readlines()
> for row in INCT:
> name, x, y, z, a, b, c, d = row.split(",")
> print aaa,
What is aaa?
> for row2 in INMRI:
> NAME, X, Y, Z, A, B, C, D = row2.split(",")
> if name == NAME:
> print aaa
For short lists this is adequate. If both lists are long the nested loop
will be slow because it has to look through all of INMRI for each line of
INCT. In this case a better solution is to put the data from INMRI in a
dictionary keyed by NAME; then you can easily test for membership.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor