Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检查输入的值是否存在于文件中的任何位置,然后打印?_Python_Python 3.x - Fatal编程技术网

Python 如何检查输入的值是否存在于文件中的任何位置,然后打印?

Python 如何检查输入的值是否存在于文件中的任何位置,然后打印?,python,python-3.x,Python,Python 3.x,我想检查文件中是否存在pupilEntered2值,并打印它,而不仅仅是第一行 def uniqueFileSearch(): pupilEntered2 = input("Please enter the pupil ID: \n") with open("pupilInformation.txt" , "r")as f: for line in f: if line.startswith(pupilEntered2):

我想检查文件中是否存在
pupilEntered2
值,并打印它,而不仅仅是第一行

def uniqueFileSearch(): 
    pupilEntered2 = input("Please enter the pupil ID:  \n")
    with open("pupilInformation.txt" , "r")as f:
        for line in f:
            if line.startswith(pupilEntered2):
                print(line)
下面是该文件的简要示例:

def uniqueFileSearch(): 
    pupilEntered2 = input("Please enter the pupil ID:  \n")
    with open("pupilInformation.txt" , "r")as f:
        for line in f:
            if line.startswith(pupilEntered2):
                print(line)

Naomi是代码中的第一行,因此它不会打印除她的以外的任何其他行。

您的代码似乎适用于我,并打印以搜索词开头的所有行。要搜索的名称必须位于行的开头

def uniqueFileSearch(): 
    pupilEntered2 = input("Please enter the pupil ID:  \n")
    with open("pupilInformation.txt" , "r")as f:
        for line in f:
            if line.startswith(pupilEntered2):
                print(line)
如果要搜索行内的任何位置,只需进行一点小改动:

def uniqueFileSearch(): 
    pupilEntered2 = input("Please enter the pupil ID:  \n")
    with open("pupilInformation.txt" , "r")as f:
        for line in f:
            if line.startswith(pupilEntered2):
                print(line)
Naomi65, Heron, 12, f
John34, Ashley, 11, m

这个代码不是这样做的吗?我觉得很好(除了缺少
else
块)。请提供一份报告。顺便说一句,欢迎使用堆栈溢出!检查and.No,它只在文件中的第一行以pupilEntered2开头时打印该行,但是我对每个学生的信息行使用了不同的行。是的,else块还有更多内容,我只是删掉了它,因为它与此无关。@GogoGT抱歉,之前忘记澄清了,您需要包括程序的所有输入(即学生ID和pupilInformation.txt的内容)和代码的最低版本(因此要么填写
else
块,要么删除它),再加上问题的描述(它应该做什么,做什么)。哦,好的,谢谢你。非常感谢你的帮助,很抱歉这是一个如此简单的问题,我只是在python的大部分领域没有受过教育。这正是我想要的,再次感谢。@ BenKeez,如果这个答案解决了你的问题,请考虑将它标记为接受。我写这篇文章只是因为你是新来的-顺便说一句,欢迎!