Search code examples
pythonpython-3.xsys

Sys arguments with while


The lines in the files will be top to bottom (one under the other)

I have 2 ".txt" file like this :

#john.txt
hello     
my
name
is
John
#jack.txt

second one is like that:

hello
your
name
is
Jack

I will compare this texts line by line but the problem is when I write

"python john.txt jack.txt " on command line sys.arg[1] and sys.argv[2] will provide the lines and compare them . so sys.argv[1] must provide lines in file one by one but I will write"python john.txt jack.txt " only one time. sample output:

python john.txt jack.txt
True
False
True
True
False

I say again. the sys.argv[1] and sys.argv[2] will provide file line by line and when the comparison ends. they will take next lines in files how can I do it ? I think it would done by using while loops but how ?


Solution

  • It will help to compare two files line by line and get expected results.

    import sys
    
    f1 = sys.argv[1]
    f2 = sys.argv[2]
    
    f1_data = open(f1, 'r')
    f2_data = open(f2, 'r')
    
    result = [True if f1_line == f2_line else False for f1_line, f2_line in zip(f1_data.readlines(), f2_data.readlines())]
    
    # Result will be in list: [True, False, True, True, False]
    print(result)