Find the current directory and file's directory
Obtain the current working directory by using os.getcwd()
and discover your file's directory with os.path.dirname(os.path.realpath(__file__))
.
Unraveling file path operations in Python
Differentiating the script directory from the current working directory
The current working directory represents the directory where your Python interpreter is invoked and is accessible via os.getcwd()
. However, this is not the same as your script's directory which is the directory where your Python script file lives. You can strategically find your script's exact location regardless of where the invocation occurs:
Resolving symbolic links
In situations where your file path includes symbolic links, navigating to the actual file location becomes critical. os.path.realpath(__file__)
can cut through the symbolic maze and lead you straight to the file:
Changing the directory, leaving __file__
untouched
You can change the current working directory using os.chdir()
. However, take note that it won't modify the value of __file__
. This fact becomes important when running scripts that depend on relative path operations:
Modern path operations with the pathlib
library
Python also allows you to navigate your file system via an object-oriented approach using pathlib
. This brings with it some intuitive advantages:
Anticipating pitfalls and pro tips
The occasional unreliable __file__
When __file__
is used in a packaged or bundled application, it may not give the expected path. Be ready to handle this variant in complex applications.
Platform-agnostic path management
The way paths are constructed differs between operating systems. Stick to using os.path.join
or pathlib
to avoid issues when moving between Unix and Windows platforms.
File operations β Path
objects to the rescue!
Starting from Python 3.6, you can cheekily slip Path
objects directly into file operations like open()
. Sweet!
Directory handling via Path
objects
Path
objects provide methods as weapons in your path manipulation armory. Use iterdir()
, glob()
, and with_name()
to wreak havoc on your file system tasks.
Was this article helpful?