简体   繁体   中英

Comparing Variables in python

I am saving modified date and file size to a text file on separate line. I am then opening the text file, reading line by line and comparing the old modified date and file size with the new one. Even though they do match, I can't for the life of me get python to agree they are the same. What am I doing wrong and how can I correct it please?

def check(movFile):
    lastModified = "%s" % time.ctime(os.path.getmtime(movFile))
    fileSize = "%s" % os.path.getsize(movFile)
    if os.path.isfile(outFile):
        checkFile = open(outFile, "r")
        line = checkFile.readlines()
        line0 = line[0]
        line1 = line[1]
        if lastModified == line0:
            print "last modified are the same"
        if fileSize == line1:
            print "file size is the same)

and here is an example of the text file:

Mon Jul  8 12:32:16 2013
7165528

I can see that both old and new are identical printing to the shell, so not sure why python is saying they are not the same.

readlines() reads whole line , including EOL character. You need to strip this character before you compare or use in operator (or startswith() method:

if lastModified == line0.strip():

should work for you.

Try removing the white spaces using

 if lastModified.strip() == line0.strip():
        print "last modified are the same"
    if fileSize.strip() == line1.strip():
        print "file size is the same"

If this does not work, other reason could be type of data. Try converting all to string type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM