Python getting script path

How to get current directory in Python?

In this article, we will take a look at how to get current directory in Python. The current directory is nothing but your working directory from which your script is getting executed.

Getting the Current Working Directory in Python

The os module has a getcwd() function using which we can find out the absolute path of the working directory.

Syntax: os.getcwd()

Parameter: None

Return Value: Returns the string which contains the absolute path of the current working directory.

Below is an example to print the current working directory in Python

# Python program get current working directory using os.getcwd() # importing os module import os # Get the current directory path current_directory = os.getcwd() # Print the current working directory print("Current working directory:", current_directory) 
Current working directory: C:\Projects\Tryouts

Get the path of the script file in Python

If you want to get the path of the current script file, you could use a variable __file__ and pass it to the realpath method of the os.path module.

Example to get the path of the current script file

# Python program get current working directory using os.getcwd() # importing os module import os # Get the current directory path current_directory = os.getcwd() # Print the current working directory print("Current working directory:", current_directory) # Get the script path and the file name foldername = os.path.basename(current_directory) scriptpath = os.path.realpath(__file__) # Print the script file absolute path print("Script file path is : " + scriptpath)
Current working directory: C:\Projects\Tryouts Script path is : C:\Projects\Tryouts\main.py

Changing the Current Working Directory in Python

If you want to change the current working directory in Python, use the chrdir() method.

Syntax: os.chdir(path)

path: The path of the new directory in the string format.

Returns: Doesn’t return any value

Example to change the current working directory in Python

# Import the os module import os # Print the current working directory print("Current working directory: ".format(os.getcwd())) # Change the current working directory os.chdir('/Projects') # Print the current working directory print("New Current working directory: ".format(os.getcwd())) 
Current working directory: C:\Projects\Tryouts New Current working directory: C:\Projects

Conclusion

To get the current working directory in Python, use the os module function os.getcwd() , and if you want to change the current directory, use the os.chrdir() method.

Источник

Python 3: Path of the Current Script File and Directory

If you want the path of the directory that the current Python script file is in:

from pathlib import Path script_dir = Path( __file__ ).parent.absolute() print( script_dir )

Using os.path

File Path

To get the file path of the current Python script:

import os script_path = os.path.abspath( __file__ ) print( script_path )

Directory

If you want the path of the directory that the current Python script file is in:

import os script_dir = os.path.abspath( os.path.dirname( __file__ ) ) print( script_dir )

__file__

__file__ is an attribute (special variable) set by Python in modules that are loaded from files (usually, but not required to be, files that have the .py extension). The attribute is not set when you’re running code inside a Python shell (the python or python3 command line program), in a Jupyter notebook, or in other cases where the module is not loaded from a file.

Although we could use __file__ by itself:

it is not guaranteed to be an absolute path (i.e., it may be a relative path). The pathlib.Path.absolute() or os.path.abspath call ensures that it is an absolute path.

References and Notes

  • The import system — Python 3 documentation
  • In Python 3.4 and up, __file__ is always an absolute path «by default, with the sole exception of __main__.__file__ when a script has been executed directly using a relative path.» See Other Language Changes — What’s New in Python 3.4.

Источник

Как получить каталог текущих файлов сценариев на Python

Как получить каталог текущих файлов сценариев на Python

  1. Python получает рабочую директорию
  2. Python получает директорию файла скрипта

Операцию с файлами и каталогами мы ввели в Python 3 basic tutorial. В этом разделе мы покажем, как получить относительный и абсолютный путь выполняющегося скрипта.

Python получает рабочую директорию

Функция os.getcwd() возвращает текущую рабочую директорию.

Если вы запустите её в Python idle в режиме ожидания, то в результате получите путь к Python IDLE.

Python получает директорию файла скрипта

Путь к файлу скрипта можно найти в global namespace с помощью специальной глобальной переменной __file__ . Она возвращает относительный путь файла скрипта относительно рабочей директории.

В приведенных ниже примерах мы покажем вам, как использовать функции, которые мы только что ввели.

import os  wd = os.getcwd() print("working directory is ", wd)  filePath = __file__ print("This script file path is ", filePath)  absFilePath = os.path.abspath(__file__) print("This script absolute path is ", absFilePath)  path, filename = os.path.split(absFilePath) print("Script file path is <>, filename is <>".format(path, filename)) 
absFilePath = os.path.abspath(__file__) 

os.path.abspath(__file__) возвращает абсолютный путь заданного относительного пути.

path, filename = os.path.split(absFilePath) 

Функция os.path.split() разделяет имя файла на чистый путь и чистое имя файла.

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Источник

Читайте также:  Сумка натуральная кожа питона
Оцените статью