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

nie*_*moy 2 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"
Run Code Online (Sandbox Code Playgroud)

svk*_*svk 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"
Run Code Online (Sandbox Code Playgroud)