Skip to main content
 首页 » 编程设计

python之正则表达式的问题

2025年05月04日26www_RR

我需要在文件中找到一个字符串;我从文件中复制并粘贴了确切的字符串到模式点,但我仍然找不到它。 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() 

文件内容如下:

firstName: test 
lastName: one 
family: family 

请您参考如下方法:

我认为 file.read() 会移动光标,因此后续调用会尝试从文件末尾开始读取。

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