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

How Can I Get the Full Path of the Current Python Script's Directory?

Mary-Kate Olsen
Release: 2024-12-09 14:28:15
Original
787 people have browsed it

How Can I Get the Full Path of the Current Python Script's Directory?

Obtaining the Full Directory Path of the Current File

To retrieve the complete path of the directory containing the current Python script, there are several approaches utilizing Python modules such as pathlib and os.path.

Python 3

For the Directory of the Running Script:

import pathlib
pathlib.Path(__file__).parent.resolve()
Copy after login

For the Current Working Directory:

import pathlib
pathlib.Path().resolve()
Copy after login

Python 2 and 3

For the Directory of the Running Script:

import os
os.path.dirname(os.path.abspath(__file__))
Copy after login

For the Current Working Directory:

import os
os.path.abspath(os.getcwd())
Copy after login

References:

  • [Python documentation on pathlib](https://docs.python.org/3/library/pathlib.html)
  • [os.path documentation (Python 2.7)](https://docs.python.org/2/library/os.path.html)
  • [os.path documentation (Python 3)](https://docs.python.org/3/library/os.path.html)
  • [os.getcwd documentation (Python 2.7)](https://docs.python.org/2/library/os.path.html#os.getcwd)
  • [os.getcwd documentation (Python 3)](https://docs.python.org/3/library/os.path.html#os.getcwd)
  • [Meaning of the file variable in Python](https://stackoverflow.com/questions/3430370/what-does-the-file-variable-mean-do)

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template