comparing contents of two files using python

前端 未结 1 1350
旧巷少年郎
旧巷少年郎 2021-01-26 11:21

I have a file name exclusionlist.txt and i have contents in it like

          import os
          import re
          import subprocess
          ......and many          


        
相关标签:
1条回答
  • 2021-01-26 12:00

    Use set intersection:

    def readImports(path):
        with open(path) as f:
            for line in f:
                # lines of form "import ___,___"
                # assuming not of form "from ___ import ___ [as ___]"
                if 'import' in line:
                    modules = line.split('import')[1]
                    for module in modules.split(','):
                        yield module.strip()
    
    linesInExclusion = set(readImports('exclusionlist.txt'))
    linesInLibraries = set(readImports('libraries.txt'))
    
    print(linesInExclusion.intersection(linesInLibraries))
    

    You can do return (line.strip() for line in f if line.strip()!='') if you want to be perfect...

    0 讨论(0)
提交回复
热议问题