Find the current directory and file’s directory [duplicate]

To get the full path to the directory a Python file is contained in, write this in that file: (Note that the incantation above won’t work if you’ve already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.) To get … Read more

How can I safely create a nested directory in Python?

On Python ≥ 3.5, use pathlib.Path.mkdir: For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it: Try os.path.exists, and consider os.makedirs for the creation. As noted in comments and elsewhere, there’s a race condition – if the directory is created … Read more

How do I list all files of a directory?

os.listdir() will get you everything that’s in a directory – files and directories. If you want just files, you could either filter this down using os.path: or you could use os.walk() which will yield two lists for each directory it visits – splitting into files and dirs for you. If you only want the top directory you can break the first time it yields or, shorter: