0

这段代码每次都返回不在文件中的日期,我不知道为什么。

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
4

2 回答 2

3

该表达式not in测试可迭代元素(列表、元组,甚至字符串)中元素的成员资格。它不像您假设的那样用于测试日期(或与此相关的任何其他内容)是否在打开的文件中。您必须逐行遍历文件并询问日期(作为字符串)是否在一行中,您可以在那里使用not in.

编辑 :

正如评论中所建议的,您可以使用:

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

...用于将文件中的内容作为字符串读取,但无论如何您需要确保文件中的日期和代码中的日期都使用相同的字符串格式。

于 2012-05-14T15:20:08.917 回答
1
 #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."
于 2012-05-14T15:25:53.797 回答