Python如果else语句不通过或不读取txt

时间:2013-11-15 15:55:41

标签: python text

我正在计算文件“Index40”中的行数。有11,436行。我将该数字保存在txt文件中作为字符串。我希望我的代码要做的是每晚计算此文件中的行数,如果等于存储为单个字符串值的数字,我希望脚本结束,否则重写文本文件中的数字并继续剧本。我遇到的问题是脚本总是认为行计数不等于txt值。这是代码:

lyrfile = r"C:\Hubble\Cimage_Project\MapData.gdb\Index40"
result = int(arcpy.GetCount_management(lyrfile).getOutput(0))
textResult = str(result)
with open(r'C:\Hubble\Cimage_Project\Index40Count.txt', 'r+') as a:
    if a == textResult:
        pass  
    else:
        a.write(textResult)
        #then do a bunch more code
        print "not passing"

2 个答案:

答案 0 :(得分:5)

您似乎正在将textResulta进行比较,后者是文件对象

如果你想要文件的内容,你需要从文件对象中读取,例如a.read()以字符串形式获取文件的全部内容。

所以我认为你正在寻找这样的东西:

with open(r'C:\Hubble\Cimage_Project\Index40Count.txt', 'r+') as a:
    contents = a.read() # read the entire file
    if contents != textResult:
        a.seek( 0 ) # seek back to the beginning of the file
        a.truncate() # truncate in case the old value was longer than the new value
        a.write(textResult)
        #then do a bunch more code
        print "not passing"

答案 1 :(得分:0)

假设“row”是一个以换行符结尾的字符串(因此,“row”是文件中的“行”),您可以执行此操作以获取总行数并使用该行与您的初始行数进行比较

with open(r'C:\Hubble\Cimage_Project\Index40Count.txt', 'r+') as f:
    allLines = f.readlines() # get all lines
    rowCount = len(allLines) # get length of all lines
    if rowCount == result:
        # do something when they are equal
    else:
        # do something when they are not equal