osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

All of a sudden code started throwing errors


> On 14 Nov 2018, at 13:51, Peter Otten <__peter__ at web.de> wrote:
> 
> Diagnosis: you managed to remove your current working directory, probably 
> because you used os.chdir() to switch to a temporary directory and then 
> forgot to switch back.
> 
> Solution: don't do that ;)
> 
> I recommend that you avoid chdir() in your code and instead always include 
> the directory into the filename.

A pattern I find myself using frequently, when I do need to ?cd?, is to write a tiny context manager:

```
import os
from contextlib import context manager

@contextmanager
def pushd(path):
    old_dir = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(old_dir)
```

(I tend to just copy this into projects where I need it (or write it again), as a whole dependency for something so tiny seems like it would be overkill :)


--
Matt Wheeler
http://funkyh.at