【发布时间】:2019-07-30 06:52:21
【问题描述】:
我正在尝试在文本文件中搜索一个字符串(由用户输入),如果该字符串存在于文本文件中,那么它将返回它的位置(文件中的位置)
我在 python 中使用了文本文件的 seek 和 tell 方法
def search(self,identity):
with open("dbase.txt", 'r') as dbase:
find = dbase.readline()
while str.casefold(find) == str.casefold(identity):
pos = dbase.tell()
find = dbase.readline()
return pos
完整代码:
class app:
''' class that takes the data and save it
into a text file name dbase.txt'''
def get_data(self):
self.name = input("Name : ")
self.add = input("Address : ")
self.mob = input("Mobile : ")
def write_data(self):
dbase = open("dbase.txt",'a')
dbase.write(self.name+"\n")
dbase.write(self.add+"\n")
dbase.write(self.mob+"\n")
dbase.close()
def read_data(self,pos):
dbase = open("dbase.txt",'r')
dbase.seek(pos)
self.name = dbase.readline()
self.add = dbase.readline()
self.mob = dbase.readline()
print(self.name)
print(self.add)
print(self.mob)
def search(self,identity):
data = open("dbase.txt", 'r').read()
desired_string = identity
if desired_string in data:
pos = data.find(desired_string)
return pos
else:
print("The desired string does not exist in the file")
call = app()
f = input("Enter :")
pos = call.search(f)
call.read_data(pos)
identity 代表我在此函数中作为参数传递的用户输入,我想在文件中匹配此身份,并且我在变量 find 中提取文件数据,因此如果 find 等于 identity 那么我想返回它是文件中的当前位置,但它不起作用,我试图在 while 循环中打印一些东西,例如 print("x") 或其他东西来检查天气 While 循环条件是否为真,因为如果它为真,那么它将打印那个“x”,但它没有打印出我得出的结论是while循环条件为假的任何东西,因此我认为故障就在这条线上。
while str.casefold(find) == str.casefold(identity):
但我不明白为什么会这样,因为我输入的字符串实际上存在于文件中。
【问题讨论】:
标签: python python-3.x