Python search a file for text using input from another file

后端 未结 5 516
梦如初夏
梦如初夏 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条回答
  •  梦毁少年i
    2021-01-20 12:06

    I think you can remove name = fd.readline() since you've already got the line in the for loop. It'll read another line in addition to the for loop, which reads one line every time. Also, I think name[1:-1] should be name, since you don't want to strip the first and last character when searching. with automatically closes the files opened.

    PS: How I'd do it:

    with open("dfile1") as dfile, open("ifile") as ifile:
        lines = "\n".join(set(dfile.read().splitlines()) & set(ifile.read().splitlines())
    print(lines)
    with open("ofile", "w") as ofile:
        ofile.write(lines)
    

    In the above solution, basically I'm taking the union (elements part of both sets) of the lines of both the files to find the common lines.

提交回复
热议问题