navigating/changing directories

Steve Holden steve at
Thu Jan 6 15:06:05 CET 2005

skip wrote:

> A simple script like the one below lets me jump through a directory 
> structure.  However, if I run it from /this/directory and within it to go to 
> /a/totally/different/directory...  I'm still actually going to be in 
> /this/directory when I exit the script.  Is it possible to have a script 
> that can drop me off into a different directory than where I initiated it 
> from?
> import os
> process = 1
> while (process):
>     # Display directories
>     for i in os.listdir(os.getcwd()):
>         if (os.path.isdir(os.path.join(os.getcwd(),i))):
>             print i
>     # Change directory
>     goto_dir = raw_input(": ")
>     if (goto_dir in os.listdir(os.getcwd())):
>         os.chdir(os.path.join(os.getcwd(),goto_dir))
>     else:
>         process = 0 # Exit
As has already been reported, under Linux a change to the current 
working directory won't affect the environment of the parent process. 
You may find that under some Windows command line interpreters that the 
  change to the working directory made by a program persists into the 
interactive session that triggered the program.

One way to achieve your desired goal, of course, is to call your program 
using a shell expansion sequence (assuming Unix-like shell 
environments), as in:

     cd ``

and then if your program outputs the path to a directory your shell's 
current working directory will be chaged as you require.

there's-always-a-way-ly y'rs  - steve
Steve Holden     
Python Web Programming
Holden Web LLC      +1 703 861 4237  +1 800 494 3119

More information about the Python-list mailing list