“Python中的程序代码不工作”;不在「;陈述
这段代码每次都返回不在文件中的日期,我不知道为什么“Python中的程序代码不工作”;不在「;陈述,python,date,Python,Date,这段代码每次都返回不在文件中的日期,我不知道为什么 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 us
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
表达式
notin
测试iterable(列表、元组甚至字符串)中元素的成员资格。如果某个日期(或任何其他相关内容)位于打开的文件中,它的工作原理与您在测试时所假设的不同。您必须逐行遍历文件,并询问日期(作为字符串)是否在一行中,您可以在该行中使用而不是
编辑:
根据评论中的建议,您可以使用:
f = open("Sales.txt")
testDate = f.read()
f.close()
。。。用于将文件中的内容作为字符串读取,但无论如何,您需要确保文件中的日期和代码中的日期都使用相同的字符串格式。表达式不在
测试iterable(列表、元组甚至字符串)中元素的成员身份。如果某个日期(或任何其他相关内容)位于打开的文件中,它的工作原理与您在测试时所假设的不同。您必须逐行遍历文件,并询问日期(作为字符串)是否在一行中,您可以在该行中使用而不是
#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."
编辑:
根据评论中的建议,您可以使用:
f = open("Sales.txt")
testDate = f.read()
f.close()
。。。用于以字符串形式读取文件中的内容,但无论如何,您需要确保文件中的日期和代码中的日期使用相同的字符串格式。1)Sales.txt的内容是什么,2)您没有定义startDate,这可能是问题所在吗?Sales.txt中的代码格式为YYYY,MM,DD,($)$$$$$$我没有定义开始日期吗?1)Sales.txt的内容是什么,2)您没有定义startDate,这可能是问题所在吗?Sales.txt中的代码格式为YYYY、MM、DD、($)$$$$$$,我没有定义开始日期吗?然后我会使用什么?当我早些时候使用它时,它正在工作,但当我开始注释它,然后稍后运行它时,它就不工作了……您可以将testDate=open(“Sales.txt”)
更改为testDate=open(“Sales.txt”).read()
,此时它将检查字符串是否在文件中的任何地方。@David您刚刚泄漏了一个open fd,所以可能不完全是那个代码(尽管它在cpython中可能至少在未来十几年内不会成为问题-良好的实践等等;)对吧,@Voo,当然-我只是压缩评论size@David是的,这对我不公平,对不起。我只是注意到,在最初的问题中,没有人对这一点发表评论,奥斯卡也没有做任何改变就接受了这一点——可以理解的是,你想保持简短。应该有不同的表述:)那么我会用什么?当我早些时候使用它时,它正在工作,但当我开始注释它,然后稍后运行它时,它就不工作了……您可以将testDate=open(“Sales.txt”)
更改为testDate=open(“Sales.txt”).read()
,此时它将检查字符串是否在文件中的任何地方。@David您刚刚泄漏了一个open fd,所以可能不完全是那个代码(尽管它在cpython中可能至少在未来十几年内不会成为问题-良好的实践等等;)对吧,@Voo,当然-我只是压缩评论size@David是的,这对我不公平,对不起。我只是注意到,在最初的问题中,没有人对这一点发表评论,奥斯卡也没有做任何改变就接受了这一点——可以理解的是,你想保持简短。应该用不同的方式来表述:)
#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."