def working_directory(path):
    """Changes working directory and returns to previous on exit."""
prev_cwd = Path.cwd()
os.chdir(path)
try:
    yield
finally:
    pass
How can I change directory with Python pathlib