Home >Backend Development >Python Tutorial >How Can I Get the Current File's Directory Path in Python?

How Can I Get the Current File's Directory Path in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 18:12:12404browse

How Can I Get the Current File's Directory Path in Python?

Accessing the Current File's Directory Path

In Python, retrieving the current file's directory path can be achieved using various techniques.

To get the directory path of the script currently being executed:

Python 3:

import pathlib
pathlib.Path(__file__).parent.resolve()

Python 2 and 3:

import os
os.path.dirname(os.path.abspath(__file__))

If the intention is to retrieve the current working directory:

Python 3:

import pathlib
pathlib.Path().resolve()

Python 2 and 3:

import os
os.path.abspath(os.getcwd())

It's important to note that file refers to the current file, which is typically the script being executed. If code is loaded from a non-file source, such as a database or online resource, file may not be defined.

For additional information, refer to the following references:

  • [pathlib in Python documentation](https://docs.python.org/3/library/pathlib.html)
  • [os.path - Python 2.7, os.path - Python 3](https://docs.python.org/2.7/library/os.path.html, https://docs.python.org/3/library/os.path.html)
  • [os.getcwd - Python 2.7, os.getcwd - Python 3](https://docs.python.org/2.7/library/os.html?#os.getcwd, https://docs.python.org/3/library/os.html#os.getcwd)
  • [What does the file variable mean/do?](https://wiki.python.org/moin/GlobalVariables)

The above is the detailed content of How Can I Get the Current File's Directory Path in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn