code: def change_dir(newdir):
      
      prevdir = os.getcwd()
      os.chdir(os.path.expanduser(newdir))
      try:
          yield
      finally:
          os.chdir(prevdir)
docs: Change directory.
  
      Adapted from http://stackoverflow.com/a/24176022