小能豆

Find the current directory and file's directory

javascript

How do I determine:

the current directory (where I was in the shell when I ran the Python script), and
where the Python file I am executing is?


阅读 116

收藏
2023-12-25

共1个答案

小能豆

In a Python script, you can use the os module to determine the current directory and the location of the Python file being executed. Here’s how you can achieve that:

1. Current Directory:

import os

# Get the current working directory
current_directory = os.getcwd()

print("Current Directory:", current_directory)

The os.getcwd() function returns the current working directory of the Python process.

2. Directory of the Python File Being Executed:

import os

# Get the absolute path of the script
script_path = os.path.abspath(__file__)

# Get the directory containing the script
script_directory = os.path.dirname(script_path)

print("Script Path:", script_path)
print("Script Directory:", script_directory)
  • __file__ is a built-in variable that represents the path of the currently executing script.
  • os.path.abspath(__file__) gets the absolute path of the script.
  • os.path.dirname(script_path) gets the directory containing the script.

Note: If you are running this code interactively in an interpreter or an environment where __file__ is not defined (e.g., in an IDE console), you might encounter an AttributeError. In such cases, it’s recommended to use a more comprehensive approach, such as using os.path.dirname(os.path.abspath(sys.argv[0])) to get the script’s directory, where sys.argv[0] is the name of the script.

import os
import sys

# Get the directory containing the script
script_directory = os.path.dirname(os.path.abspath(sys.argv[0]))

print("Script Directory:", script_directory)

This method is more robust and works even if __file__ is not defined.

2023-12-25