Python if else语句未传递或未读取tx

2024-09-27 23:15:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在计算文件“Index40”中的行数。一共有11436排。我把这个数字以字符串的形式保存在一个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"

Tags: 文件字符串代码txtproject脚本数字result
2条回答

似乎您正在比较textResulta,后者是文件对象。你知道吗

如果需要文件的内容,则需要从file对象中读取,例如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"

假设“行”是一个以新行字符结尾的字符串(因此,“行”是文件中的“行”),您可以这样做来获得总行数,并使用它与初始行数进行比较

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

相关问题 更多 >

    热门问题