Illusionist
Illusionist

Reputation: 5509

compare two files

I have two files in this format

file1= filename val1 val2
file2= filename val3 val4

I want to compare filenames and if they have the same names , i want to get a third file like this-

filename val1 val2 val3 val4

I am picking a filename from file1 and going across file2 to see if i get it. Then seeking pointer back to the top of file2 for the next filename..is there a more efficient way of doing it?

Upvotes: 3

Views: 287

Answers (2)

Greg Hewgill
Greg Hewgill

Reputation: 994727

It sounds like what you're looking for is the standard join command (not Python, but a standard Unix shell utility). Here's a snip from the manual page on a system (that seems to have more detail than the Linux man page for join):

        join phonedir names

        If the phonedir file contains the following names:

        Adams A.        555-6235
        Dickerson B.    555-1842
        Erwin G.        555-1234
        Jackson J.      555-0256
        Lewis B.        555-3237
        Norwood M.      555-5341
        Smartt D.       555-1540
        Wright M.       555-1234
        Xandy G.        555-5015

        and the names file contains these names and department numbers:

        Erwin           Dept. 389
        Frost           Dept. 217
        Nicholson       Dept. 311
        Norwood         Dept. 454
        Wright          Dept. 520
        Xandy           Dept. 999

        the join command displays:

        Erwin G.        555-1234        Dept. 389
        Norwood M.      555-5341        Dept. 454
        Wright M.       555-1234        Dept. 520
        Xandy G.        555-5015        Dept. 999

Upvotes: 4

Nicolas78
Nicolas78

Reputation: 5144

create a dict file2[filename] = (val3, val4). you can create this once, then lookup time for a given filename you get from file1 takes constant time (ie is more or less independent on the size of file2)

Upvotes: 2

Related Questions