简体   繁体   中英

Program code in Python not working “not in” statement

This code is returning the Date not being in the file every time, and I don't know why.

testDate = open("Sales.txt")

#Declaring variables for later in the program
printNum = 1

newcost = 0

startTestLoop = 1

endTestLoop = 1

#Creating a loop in case input is invalid
while startTestLoop > 0:

    #Asking user for start date
    #startDate = raw_input("Please input the desired start date in the form YYYY,MM,DD: ")


    #Checking if input is valid, and arranging it to be used later
    try :
        startDate = startDate.strip().split(',')
        startYear = startDate[0]
        startMonth = startDate[1]
        startDay = startDate[2]
        startYear = int(startYear)
        startMonth = int(startMonth)
        startDay = int(startDay)
        startDate = date(startYear, startMonth, startDay)
    #Informing user of invalid input
    except:
        "That is invalid input."
        print
    #EndTry



    #Testing to see if date is in the file, and informing user
    if startDate not in testDate:
        print "That date is not in the file."
    #Exiting out of loop if data is fine 
    else:
        startTestLoop -= 1
        print "Aokay"
    #EndIf

The expression not in tests membership of an element in an iterable (a list, a tuple, even a string). It doesn't work like you assume for testing if a date (or anything else for that matter) is inside an open file. You'll have to traverse the file line by line and ask if the date (as a string) is in a line, there you can use not in .

EDIT :

As suggested in the comments, you could use:

f = open("Sales.txt")
testDate = f.read()
f.close()

... For reading the contents in the file as a string, but anyway you need to make sure that both the dates in the file and the date in your code are using the same string formatting.

 #assume your Sales.txt contains a list of dates split by space
  if startDate not in testDate.read().split():
        print "That date is not in the file."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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