Python's resultant issues
Question: I'm new of Python and i'm stuck on this. I need to check if i can find a
string in a file. I have created the file ContEAN.py

the code:

    
    
    import sys
    
    for arg in sys.argv:
    inputEAN=arg
    EAN = open("/home/master/Documenti/Progetti/eanFZ.txt","r")
    
    riga=EAN.readlines()
    
    EAN.close()
    
    print inputEAN
    
    for i in range(len(riga)):
    if inputEAN == riga[i]:
        print "OK"
    

From Command line:

> $ python ContEAN.py 455

where "455" will be the value of inputEAN

and this is the content of eanFZ.txt:

    
    
    7777
    777
    0000000000156
    0000000015
    455
    9999
    85485
    656565
    

the problem is that i never have an ok as ultimate result and i don't know
why...


Answer: First of all, the readlines() method returns an iterable object which can be
iterated over in the loop. Each iteration will use the next line of the file.

Secondly, the lines of the file have a hidden newline character at the end, so
it is not 'equal' to the string from argv. This can be removed with the
rstrip() method.

    
    
    for i in riga:
        if inputEAN == i.rstrip():
            print "OK"
    

(You may also want to check indentation. You need to go to a new indentation
level after each for line and each if line. I have assumed this was due to
copy and paste.)

