如何在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无法识别文本文件中的所有不同行,因此认为它都是一行。我将如何安排它工作?或者,如果您发现我的代码有任何明显问题,我们将不胜感激。

比约恩

您只检查匹配的第一行

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在 free pascal 中编辑文本文件的特定部分?

如何在文本文件中搜索特定整数

如何在Emacs中仅查看和编辑文本文件的一小部分

在Python中编辑文本文件中的特定行

Python编辑文本文件中的特定单词

如何在子文件夹中搜索特定的文本文件

如何在我的终端中编辑文本文件

Inno Setup-如何在设置过程中从文本文件编辑特定行?

如何在文本文件中搜索字符串并根据结果执行特定操作

如何使用python编辑文本文件中的数据?

如何在 C 中读取文本文件的特定部分?

如何在Lucene 3.0.2中索引和搜索文本文件?

如何在python 3.6中编辑多行文本文件?

我如何让python3在文本文件中搜索特定的字符串

你如何在python的文本文件中搜索某个东西?

如何在Python中搜索每个本地文本文件?

如何在文本文件中搜索单词并使用Python打印整行?

如何在目录中的所有文本文件中搜索字符串并将找到的结果放在 Python 中的文本文件中

如何在从Python中的文本文件生成的嵌套列表中选择列表项

在 Python 中编辑文本文件后,如何将文本文件重新加载到 JSON 中?

如何在Python中从文本文件中提取特定数据?

如何在python的文本文件中查找特定值

如何在python中从文本文件中添加和减去值

我如何在多个文本文件中搜索模式并写入新的多个文本文件

如何在Python中从文本文件读取input()

如何在python中重命名文本文件?

如何在python中复制文本文件

如何在Python中从文本文件打印名称

如何在python中打开文本文件?