相当适合编程和python的初学者,我目前正在为图书馆图书管理员编写程序。我正在尝试从文本文件中选择一个字符串,因此,当用户键入必须签入书籍用户名的用户时,它将附带书籍和信息。但是,当我执行此操作时,将打印整个内容,而不是打印用户号所在的行。 请查看我的代码:
searchphrase = raw_input("Please provide Your user ID:")
searchfile = open("Librarybooks.txt","r")
for line in searchfile:
if searchphrase in line:
print line
else:
print "User not identified or invalid entry, please restart program"
break
我认为可能是python无法识别文本文件中的所有不同行,因此认为它全部都是一行。我将如何布置它来工作?或者,如果您发现我的代码有任何明显的问题,将不胜感激。
答案 0 :(得分:1)
您只检查直到不匹配的第一行:
searchphrase = raw_input("Please provide Your user ID:")
searchfile = open("Librarybooks.txt","r")
for line in searchfile:
if searchphrase in line: # <== if it matches, then print and go to next line..
print line
else: # <== if id doesn't match, exit the for loop
print "User not identified or invalid entry, please restart program"
break
尝试这样的方法:
for line in searchfile:
if searchphrase in line: # <== if matches, then print the line and break out of the for loop
print line
break
else: # <== if the for loop finished without breaking, then the searchphrase was not in the file
print "User not identified or invalid entry, please restart program"
这在for循环上使用else子句。
调试这类问题的一种简单方法是在某些更改发生之前(和之后)打印出有趣的变量。例如:
for line in searchfile:
print "LINE: [%s]" % line # I put it inside [] to check if there are any spaces at the end.
这样,您可以验证您的假设是正确的。
您的IDE可能具有调试器,可让您在漂亮的可视化用户界面中设置断点并检查变量。