There area unit 2 best practices to follow once victimization this method:
Catch the exception (WindowsError, OS Error) on invalid path. If the exception is thrown, don’t perform any algorithmic operations, particularly damaging ones. they’ll operate the recent path and not the new one.
Return to your recent directory once you are done. this will be wiped out AN exception-safe manner by wrapping your chdir decision in a very context manager.