2012-05-14 43 views
0

此代碼每次都返回不在文件中的日期,我不知道爲什麼。Python中的程序代碼不工作「not in」語句

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 
+0

1)Sales.txt的內容是什麼,2)你沒有定義startDate,這可能是問題嗎? – BluePeppers

+0

Sales.txt中的代碼格式爲YYYY,MM,DD,($)$$$。$$,我是不是定義開始日期? – user1359077

回答

3

在一個可迭代的元件的表達not in測試成員(列表,一個元組,即使一個字符串)。它不起作用,就像您假設某個日期(或其他任何事情)在打開的文件中一樣。您必須逐行遍歷文件並詢問日期(作爲字符串)是否在一行中,您可以使用not in

編輯:

正如評論所說,你可以使用:

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

...對於文件作爲字符串中讀取內容,但無論如何,你需要確保文件中的日期和代碼中的日期都使用相同的字符串格式。

+0

然後我會用什麼?當我以前使用它時正在工作,但是當我開始評論它,然後在後來運行它時,它不起作用... – user1359077

+0

@ user1359077我更新了我的答案。 –

+3

您可以將'testDate = open(「Sales.txt」)'改爲'testDate = open(「Sales.txt」).read()',此時它會檢查字符串是否在文件中的任何位置。 –

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."