Home >Backend Development >Python Tutorial >How Do I Get the Current Directory and File Location in Python?

How Do I Get the Current Directory and File Location in Python?

DDD
DDDOriginal
2024-12-09 05:18:10333browse

How Do I Get the Current Directory and File Location in Python?

Get Current Directory and File Location in Python

Determining the current directory and the location of the Python file being executed can be useful for various purposes. Here's how to achieve it:

1. Current Directory

To obtain the current working directory (where the Python script was executed from the shell), use the following Python code:

import os
cwd = os.getcwd()

This will provide the absolute path to the current directory, even if a different directory was specified in the shell prior to running the Python script.

2. Python File Location

To get the full path to the directory where the Python file is stored, use this code within the file:

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

__file__ is a constant that represents the name of the currently executing Python file relative to the current working directory. os.path.dirname extracts the directory name from the provided path, while os.path.realpath ensures that any symbolic links in the path are resolved.

Additional Resources:

  • [os module](https://docs.python.org/3/library/os.html)
  • [os.getcwd](https://docs.python.org/3/library/os.html#os.getcwd)
  • [os.path module](https://docs.python.org/3/library/os.path.html)
  • [os.path.dirname](https://docs.python.org/3/library/os.path.html#os.path.dirname)
  • [os.path.realpath](https://docs.python.org/3/library/os.path.html#os.path.realpath)

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