Reputation: 192
I am trying to create a simple search engine to look inside a file. In order to reuse the code I separated the search function, but for some reason it just doesn't work the second time round.
The first time round it shows the result as it should but the second time I type a name it doesn't give me any result at all. Its like the c
variable is not going in to the searchpart(c, path)
function the second time round.
import os
def searchpart(c, path):
employees = os.walk(path)
for root, dirs, files in employees:
names = os.path.basename(root)
if c.lower() in names.lower():
print(root)
os.chdir(root)
for i in os.listdir():
print("-----> {}".format(i))
def welcomepart(path):
# this function allows to reuse the application after a name is search.
c = input("\n-------> please introduce the name? \n")
searchpart(c, path)
def mainfuntion():
path = 'WORKERS'
invalid_input = True
print('______________ Welcome ______________ \n ')
while invalid_input:
welcomepart(path)
mainfuntion()
Upvotes: 1
Views: 438
Reputation: 39422
This work-around seems to fix the problem:
def searchpart(c, path):
cwd = os.getcwd()
employees = os.walk(path)
for root, dirs, files in employees:
names = os.path.basename(root)
if c.lower() in names.lower():
print(root)
os.chdir(root)
for i in os.listdir():
print("-----> {}".format(i))
os.chdir(cwd)
It just remembers which directory you were in before the function call and changes back before returning.
However, I'm sure there will be a solution where the line: os.chdir(root)
is not needed.
Upvotes: 1