简体   繁体   English

比较python中的变量

[英]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. 即使他们确实匹配,我也不能为我的生活让python同意他们是一样的。 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. 我可以看到旧的和新的都是相同的打印到shell,所以不知道为什么python说它们不一样。

readlines() reads whole line , including EOL character. readlines()读取整行 ,包括EOL字符。 You need to strip this character before you compare or use in operator (or startswith() method: 你需要你比较或使用之前剥离这个人物in运营商(或startswith()方法:

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. 尝试将all转换为字符串类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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