Home >Backend Development >Python Tutorial >How Do I Get the Current and Script Directories in Python?

How Do I Get the Current and Script Directories in Python?

DDD
DDDOriginal
2024-12-10 13:26:16656browse

How Do I Get the Current and Script Directories in Python?

Determining the Current and File Directories in Python

Knowing the current directory and the location of the currently executing Python file can be useful in many scenarios. Here's how to retrieve this information:

Finding the Current Directory

To obtain the full path to the current working directory where you ran the Python script, use the following code:

import os
cwd = os.getcwd()

Locating the Script's File Directory

To determine the directory containing the running Python file, utilize the following incantation:

import os
dir_path = os.path.dirname(os.path.realpath(__file__))

This approach ensures that the correct directory is retrieved regardless of any changes made to the current working directory using os.chdir().

References

  • [os and os.path modules](https://docs.python.org/3/library/os.html)
  • [__file__ constant](https://docs.python.org/3/library/__builtin__.html#file)
  • [os.path.realpath()](https://docs.python.org/3/library/os.path.html#os.path.realpath)
  • [os.path.dirname()](https://docs.python.org/3/library/os.path.html#os.path.dirname)
  • [os.getcwd()](https://docs.python.org/3/library/os.html#os.getcwd)
  • [os.chdir()](https://docs.python.org/3/library/os.html#os.chdir)

The above is the detailed content of How Do I Get the Current and Script Directories 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