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

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]))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.