A few years ago I wrote a Django app for a client. One part of the app called
os.getcwd(), and another part (that I thought of as completely separate) used a temporary directory to build PDFs.
Occasionally the call to
os.getcwd() would raise an error. I was confused. How can there be no current directory? It took me a while to figure it out, but in hindsight it’s kind of obvious (as these things often are).
My PDF-building code created a temporary directory, set that directory to be the current working directory, and then removed the directory once the PDF was built. After that, there was no current working directory. It’s easy to demonstrate —
$ python3 Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> import tempfile >>> temp_dir = tempfile.TemporaryDirectory() >>> os.chdir(temp_dir.name) >>> os.getcwd() '/private/var/folders/9f/4zptd_j10dx343w0r7tvkm0r0000gn/T/tmpfcwpe1xs' >>> temp_dir.cleanup() >>> os.getcwd() Traceback (most recent call last): File "", line 1, in FileNotFoundError: [Errno 2] No such file or directory >>>
I have a feeling I’m not the only developer who was foolish enough to assume that
os.getcwd() would never fail. At least now I know better, and you do too!