在 2 个不同文件中查找公共行

我试图在 2 个不同的文件中找到公共行,并试图在一个新的文本文件中列出它们。我在下面写了这个,但它没有找到公地,只写我在 arg2 中提供的任何文件。请帮我排除故障。


#!/usr/bin/python


import sys



def find_common_lines(arg1, arg2, arg3):

    fh1 = open(arg1, 'r+')

    fh2 = open(arg2, 'r+')

    with open(arg3, 'w+') as f:

        for line in fh1 and fh2:

            if line:

                f.write(line)


    fh1.close()

    fh2.close()



number_of_arguments = len(sys.argv) - 1

if number_of_arguments < 3:

    print("ERROR:\tThe script is called with less than 3 arguments, but it needs 3!")

    print("Usage:\tfind_common_lines.py <file1> <file2> <output_filepath>")

else:

    arg1 = sys.argv[1]

    arg2 = sys.argv[2]

    arg3 = sys.argv[3]

    find_common_lines(arg1, arg2, arg3)

所以,基本上我想让这个脚本做的是:


文件A


AAB

BBC

DDE

GGC

文件B


123

AAB

DDE

345

GHY

GJK

文件 C


AAB

DDE

谢谢!!!


人到中年有点甜
浏览 132回答 3
3回答

元芳怎么了

首先,使用“and”运算符时需要给出2条逻辑语句,现在您使用的是1条逻辑语句,然后直接在for循环中输入fh2。尝试将代码更改为以下几行:for line in fh1 and fh2:&nbsp; &nbsp; if line:&nbsp; &nbsp; &nbsp; &nbsp; f.write(line)到if line in fh1:&nbsp; &nbsp; if line in fh2:&nbsp; &nbsp; &nbsp; &nbsp; f.write(line)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python