Home > Backend Development > Python Tutorial > How Can I Get the Current Script's File Path and Name in Python?

How Can I Get the Current Script's File Path and Name in Python?

Mary-Kate Olsen
Release: 2024-12-11 18:43:11
Original
387 people have browsed it

How Can I Get the Current Script's File Path and Name in Python?

Obtaining the Current Script's File Path and Name

In Python, one may encounter scenarios where scripts call other scripts, and there's a need to retrieve the executing script's file path from within the called script. Understanding the mechanism to achieve this is crucial.

One solution involves using the Python keyword __file__. This global variable represents the path and name of the currently executing file. For instance, consider the following code block:

import os

# Fetch the current script's full path
script_path = __file__

# Extract the file name without the full path
script_name = os.path.basename(script_path)

# Print the file name and path
print(f"Script Name: {script_name}")
print(f"Script Path: {script_path}")
Copy after login

This code allows you to access both the file name and the entire file path of the active script. By leveraging this technique, you can bypass the need to pass such information as arguments from calling scripts.

Another variation, as suggested by others, involves utilizing os.path.realpath to resolve any potential symlinks. For instance:

import os

# Get the full path of the script
script_path = __file__

# Resolve any symlinks
real_script_path = os.path.realpath(script_path)

# Extract the file name and path with the symlinks resolved
script_name = os.path.basename(real_script_path)
script_path = os.path.dirname(real_script_path)

# Print the resolved file name and path
print(f"Resolved Script Name: {script_name}")
print(f"Resolved Script Path: {script_path}")
Copy after login

By incorporating these techniques into your code, you can effectively retrieve the file path and name of the currently executing script, providing a solid foundation for script interaction.

The above is the detailed content of How Can I Get the Current Script's File Path and Name in Python?. 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