I need to perform an action without changing the global working directory. My case is I have a few folders, and in each, there are a few files. I need to do some computations using those files. Initially, I tried the following:
with os.chdir('/directory'):
...some code needing execution inside
but got AttributeError: __enter__. After reading up online using with seems not to be an option. Therefore I'm looking to find another elegant way of doing so.
I also tried just using os statements like so:
cwd = os.getcwd()
os.chdir('/directory')
..run code inside directory
os.chdir(cwd)
but this is a pain during debugging and seems like a bad practice.
os.chdirreturnsNone, which is not a context manager. That doesn't mean you can't find or write an appropriate context manager.contextlib.chdirin Python 3.11. If you are using an earlier version, you can also refer to its source code.subprocesswhich has acwdargument: stackoverflow.com/questions/21406887/…