我有一个 .txt 文件,其中包含许多客户的详细信息、出生日期和地址。我指示 Python 访问该文件并要求我输入以搜索特定的出生年份或邮政编码。 我在函数内部调用了该函数,以便在完成每次搜索时它会要求我输入。 该代码在第一次尝试时有效 然而问题是在一次搜索之后,它会跳过“for”循环并始终返回“找不到匹配”,即使我的输入存在于文件中
file = input("Enter file name: ")
custlist= open(file)
#define our function to search for component
def search():
searchword = input()
result = None
for line in custlist :
cust = line.rstrip()
if searchword in cust:
result = line
print(result)
if result is None :
print('match not found')
search()
search()
custlist
不是 list
,它是一个打开的文件对象。打开的文件对象是迭代器,而不是集合;一旦一行被消耗,它就消失了,除非返回到开头,否则您无法重新启动新循环。
您需要其中之一:
custlist= open(file)
更改为 custlist= list(open(file))
(缓存文件行一次并重新使用它们,或者custlist.seek(0)
。