Find all the numbers in one file that are not in another file in python

前端 未结 5 2077
灰色年华
灰色年华 2021-01-04 02:08

There are two files, say FileA and FileB and we need to find all the numbers that are in FileA which is not there in FileB. All the numbers in the FileA are sorted and all t

5条回答
  •  萌比男神i
    2021-01-04 02:50

    A simple solution based on file reading (asuming that each line hold a number):

    results = []
    with open('file1.csv') as file1, open('file2.csv') as file2:
            var1 = file1.readline()
            var2 = file2.readline()
            while var1:
                while var1 and var2:
                    if int(var1) < int(var2):
                        results.append(int(var1))
                        var1 = file1.readline()
                    elif int(var1) > int(var2):
                        var2 = file2.readline()
                    elif int(var1) == int(var2):
                        var1 = file1.readline()
                        var2 = file2.readline()
                if var1:
                    results.append(int(var1))
                    var1 = file1.readline()
    print(results)
    output = [2, 5, 7, 9]
    

提交回复
热议问题