niemoy
niemoy

Reputation: 87

Python if else statement not passing or not reading txt

I am counting the number of rows in a file "Index40". There are 11,436 rows. I save that number in a txt file as a string. What I want my code to do is count the number of rows in this file each night and if is equal to the number stored as a single string value I want the script to end, otherwise rewrite the number in the text file and continue on with the script. The problem Im having is the script always thinks the row count is not equal to the txt value. Here is the code:

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"

Upvotes: 1

Views: 234

Answers (2)

MxLDevs
MxLDevs

Reputation: 19546

Assuming a "row" is a string that ends with a new-line character (therefore, a "row" is a "line" in your file), you can do this to get the total number of rows and use that to compare with your initial row count

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

Upvotes: 0

svk
svk

Reputation: 5919

It seems like you're comparing textResult with a, which is the file object.

If you want the contents of the file, you'll need to read from the file object, e.g. a.read() to get the entire contents of the file as a string.

So I think you're looking for something like this:

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"

Upvotes: 5

Related Questions