正则表达式的麻烦

Bra*_*don 1 python regex file-io

我需要在文件中找到一个字符串; 我将文件中的确切字符串复制并粘贴到模式点,但我仍然无法找到它.print除第一个名称外,这些命令返回空字符串.这是我的代码:

def fillWindow(self,student):
    global fileDirectory
    location = path.join(fileDirectory, student + '.txt')
    file = open(location, 'r')

    # find item in list and then place it in the text box   
    firstName = re.findall(r'firstName\:', file.read())
    print(firstName)
    self.firstNameBox.insert(0,'firstName')

    lastName = re.findall(r'lastName\:', file.read())
    print(lastName)
    self.lastNameBox.insert(0,'lastName')

    family = re.findall(r'family\:', file.read())
    print(family)
    self.familyNameBox.insert(0,'family')

    file.close()
Run Code Online (Sandbox Code Playgroud)

以下是文件的内容:

firstName: test
lastName: one
family: family
Run Code Online (Sandbox Code Playgroud)

Tom*_*ott 5

我认为file.read()将移动光标,以便后续调用将尝试从文件末尾读取.

您可以先将文件的内容读入变量,然后在其中执行正则表达式搜索.