[Tutor] Problem with 'IF' condition

Alan Gauld alan.gauld at yahoo.co.uk
Fri Dec 1 12:33:02 EST 2017

On 01/12/17 14:02, a.ajmera at incycleautomation.com wrote:

> - If you see in my code, I'm writing to "test1.txt" and saving that value in "nao" as well.
> On the other side, I'm reading from "test3.txt" and saving that value in "abb" just like above.
> Now, my goal is to compare these two variables nao & abb. As it written below.
> However, result never gives me "true" when actually this both variable contain same values.

Are you absolutely sure they are the same? Have you checked, for example
for newline characters or other whitespeace?
You could do that by printing the repr() of the values:

print repr(nao), repr(abb)

Now simplifying your code slightly:

> x = "C:/FTP_Folder/test1.txt"
> f = open(x)
> r = f.read(500)
> f.close()

> f1 = open(x,'w')
> z = f1.write("1")
> f1.close()

Note that this will have deleted everything in x
and replaced it with "1"

> f = open(x)
> r0 = f.read(500)

r0 will now contain '1'

> nao = r0

As will nao

> f.close()

> y = "C:/FTP_Folder/test3.txt"
> f2 = open(y)
> r1 = f2.read(500)
> abb = r1

abb now contains whatever was in test3.txt.
Did it contain '1'?

> if nao == abb:
>  print("Positions are same")
>  print r, r1

r contains the original contents of test1
r1 contains the content of test3

> else:
>  print("not same")
>  print nao, abb

whereas nao contains '1' and abb contains the
same as r1

Is my interpretation what you see, and is it what
you expect?

In future with thee kinds of issues its good
to include an actual cut n paste of the program

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list