我需要在文件中找到一个字符串; 我将文件中的确切字符串复制并粘贴到模式点,但我仍然无法找到它.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) 在我的程序中,我有一个文件,然后我读取for循环中的所有行,检查每一行的开头.然后将每一行添加为变量.这里有40多行,它们几乎都是一样的但是其中一个elif语句并没有返回真实的.startswith无效.无论如何这里的文件内容基本上是一堆保存的信息fN将是我保存的变量,john将是我想要的.所以这个方法就是这样做的,或者它是假设的
fN:john
fP:1
fE:father email
mN:mother name
mP:1
mE:mother email @ bomg.com
a:1233 adress lane
c:city
s:state
zC:1234534
hP:(1928)phone-1123
cP:1113333
eN:emergancy
eNu:number
c1N:cluubiie 1
c1G:1st
c1B:1-23-34
c2N:clubbie 2
c2G:grade 2
c2B:birth 2
c3N:clubb 3
c3G:grade 3
c3B:birth 3
Run Code Online (Sandbox Code Playgroud)
方法
def fillWindow(self,student):
global fileDirectory
location = os.path.join(fileDirectory, student + '.txt')
file = open(location, 'r')
for line in file.xreadlines():
if line.startswith('fN'):
fN = line.split(':')[1]
elif line.startswith('fP'):
fP = line.split(':')[1]
elif line.startswith('fE'):
fE = line.split(':')[1]
elif line.startswith('mN'):
mN = line.split(':')[1]
elif line.startswith('mP'):
mP …Run Code Online (Sandbox Code Playgroud)