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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 22:55:10540browse

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

Determining the Full Path of Current File's Directory

Getting the full path of the current file's directory can be achieved in Python using the special file variable.

Pathlib Approach (Python 3):

For the directory of the running script:

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

os.path Module Approach (Python 2 and 3):

For the directory of the running script:

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

Note: It's crucial to note that file contains two underscores before and after it (not just one).

Extracting the current working directory (cwd):

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

In summary, these techniques enable you to determine the full path to the directory containing the current Python script or the current working directory.

The above is the detailed content of How Can I Get the Full Path of My Current File's Directory 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