Search code examples
python-3.xipythoncd

How to change working directory of Python script during execution?


I am working on a personal project and I have been stuck here. I want to change the working directory of my program during its execution but it is not working and there is also no error.

def google_search(search_term, api, cse, num = 10):
    service = build("customsearch", "v1", developerKey = api)
    res = service.cse().list(q = search_term, cx = cse).execute()

    #Creating new folder with search term
    if not os.path.exists(search_term):             
        print('Creating project: ' + search_term)
        os.makedirs(search_term)

    return res['items']
    os.chdir("../test 1/%s" %search_term)

When I execute the entire script I get no error, the script executes completely but the directory doesn't change to the directory I have just created using the 'search_term'.

If I individually run the command below in ipython shell(using the search_term value), it executes and takes me to the intended directory.

os.chdir("../test 1/%s" %search_term)

It is working as an individual command when I put in the name of the directory directly but it is not working when I use it in the whole script.


Solution

  • There is return statement before os.chdir, so that line is not executed.