0

Hi all,

I have two text files

file1
1234
13454
93837
82739
.
.
.

File2
comp i
93837 -4.52
82739 -2.2
1234 -2.36
13454 -2.25

I tried a python script to compare files and it should ideally do following search CID
from file1 in file2 and append i value to file1. but unfortunately it is not working can anybody help

file1=open("f1.txt","r")
file2=open("f2.txt","r")
for line1 in file1.readlines():
  for line2 in file2.readlines():
    if line1 in line2:
      print line2

Thanks
n

Edited by Narue: Added code tags

2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by Gribouillis
0

If the second file is not too long, I suggest to load it and build a dictionary of pairs (key, value) with its content. It will be much faster than rereading the file for every entry in file 1

def makedict(filename):
    pairs = list()
    with open(filename) as f:
        for line in f:
            key, value = line.strip().split()
            pairs.append((key, value))
    result = dict(pairs)
    # if this fails, it means that some keys appear more than once in file 2
    assert len(result) == len(pairs)
    return result


if __name__ == "__main__":
    D = makedict("f2.txt")
    with open("f1.txt") as f:
        for line in f:
            key = line.strip()
            if key in D:
                print("{0}\t{1}".format(key, D[key]))
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.