如何在Python中搜索、选择和编辑文本文件的特定部分

2024-04-19 11:51:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程和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不能识别文本文件中的所有不同行,所以认为它们都是一行。我该如何安排工作?或者,如果您能看到我的代码有任何明显的问题,我们将不胜感激


Tags: 字符串代码用户in程序管理员编程line
1条回答
网友
1楼 · 发布于 2024-04-19 11:51:56

只有在第一行不匹配时才进行检查:

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可能有一个调试器,允许您在一个非常直观的用户界面中设置断点和检查变量

相关问题 更多 >