Python search a file for text using input from another file

后端 未结 5 570
梦如初夏
梦如初夏 2021-01-20 11:24

I\'m new to python and programming. I need some help with a python script. There are two files each containing email addresses (more than 5000 lines). Input file contains em

5条回答
  •  青春惊慌失措
    2021-01-20 11:55

    mitan8 gives the problem you have, but this is what I would do instead:

    with open(inputfile, "r") as f:
        names = set(i.strip() for i in f)
    
    output = []
    
    with open(datafile, "r") as f:
        for name in f:
            if name.strip() in names:
                print name
    

    This avoids reading the larger datafile into memory.

    If you want to write to an output file, you could do this for the second with statement:

    with open(datafile, "r") as i, open(outputfile, "w") as o:
        for name in i:
            if name.strip() in names:
                o.write(name)
    

提交回复
热议问题