Python full path script

Get the path of the currently executing python script using import. (Python recipe) by Jitender Cheema

William B. good one, understood.How to do in Windows ??

Why not use sys.path[0] ? Statement ‘print sys.path[0]’ does what you want, see http://docs.python.org/lib/module-sys.html

addition: full path to running script. Well, to get the path + script file do something like: ‘print os.path.join(sys.path[0], sys.argv[0])’

As I said there can be many ways, one of the way is using: sys.path[0] sys.path is List of paths.. Try this in python interpreter import sys print sys.path # prints out a whole list of python module paths.. print sys.path[0] # prints out » Now try same as a python script and compare: import sys print sys.path # prints out a whole list of python module paths.. print sys.path[0] # prints out cwd

The current directory can be interpreted more than one way. In order to understand what is going on with the following short section of code, put it in a file named pwd.py, then do the following:

mkdir junk cd junk python ../pwd.py 

You need to make sure that your current working directory (the cd command destination) is not the same as the directory containing the Python script. After that it is self explanatory except for the .EXE path. Try running the script through PY2EXE first, and this will make more sense.

import os,sys print "CWD: ",os.getcwd() print "Script: ",sys.argv[0] print ".EXE: ",os.path.dirname(sys.executable) print "Script dir: ", os.path.realpath(os.path.dirname(sys.argv[0])) pathname, scriptname = os.path.split(sys.argv[0]) print "Relative script dir: ",pathname print "Script dir: ", os.path.abspath(pathname) 

sys.path[0] is not the same. Here’s my (slightly) cleaned up version:

import sys import os, os.path def get_my_path(): import fake path = str(fake).split()[3][1:-9] os.remove( os.path.join( path, 'fake.pyc' ) ) return path def do(): print "sys.path[0]: %s" % sys.path[0] print "os.getcwd(): %s" % os.getcwd() print "get_my_path(): %s" % get_my_path()

Import this module from a different directory (make sure it’s in your PYTHONPATH) and invoke do(). You’ll see that the first two paths are the directory you’re invoking from, but the third is the directory containing the module.

Читайте также:  Sass convert css to sass

Thanks to all for your inputs.

Just summarizing what worked best for me (I needed to get the path of the current module). It was tested on both Linux and Windows, with all the usages I could think of.

os.path.dirname( os.path.realpath( __file__ ) ) 

The reason for the additionnal call to os.path.realpath() is that omitting it will only work if you run the script by specifying its full path (or, under Windows, if you only type the python script name — this is because Windows has Python.exe associated to that extension and will specify the full path of the script whenever it invokes it).

So, to import from a location relative to the current path, you can do:

import os # BASE_PATH is the absolute path of ../.. relative to this script location BASE_PATH = reduce (lambda l,r: l + os.path.sep + r, os.path.dirname( os.path.realpath( __file__ ) ).split( os.path.sep )[:-2] ) # add ../../scripts (relative to the file (!) and not to the CWD) sys.path.append( os.path.join( BASE_PATH, "scripts" ) ) import foobar if __name__ == '__main__': . 

i get the same path info for either BASE_PATH. very clever idea — would like to make it work. if you can, please see if i missed soemthing? i created a folder one level up names scripts, and put a module in there names foo.py foo.py is just a hello world. the error is no module foo found. tia, greg

!/usr/bin/python

import os from os import path import sys

BASE_PATH is the absolute path of ../.. relative to this script location

BASE_PATH = reduce (lambda l,r: l + os.path.sep + r, os.path.dirname( os.path.realpath( __file__ ) ).split( os.path.sep )[:-2] )

print BASE_PATH, ‘original base path’

add ../../scripts (relative to the file (!) and not to the CWD)

sys.path.append( os.path.join( BASE_PATH, «../scripts/» ) )

print BASE_PATH, ‘modified base path’

Источник

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.

Читайте также:  Css content box width

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.

Источник

How to get an absolute path in Python

Operating systems such as Windows, Linux, or macOS have different path structures in which operating system files are stored.

Therefore when you run Python scripts on these machines and want to fetch files or directories, you want to find the file’s absolute path relative to the current directory automatically instead of hardcoding it for every system.

An absolute path is also known as the full path and starts with / in Linux and macOS and C:/ on Windows.

To find an absolute path in Python you import the os module then you can find the current working directory using os.path.abspath(«insert-file-name-here») in your Python script.

What is an absolute path in Python?

An absolute path in Python is the full path starting from the root of the operating file system up until the working directory.

So let’s say you run your Python code in /Users/dannysteenman/home/projects/example-project/app.py . This is the entry point where you run the top-level code of your python module.

Then this is the absolute path of your working directory /Users/dannysteenman/home/projects/example-project/ .

How to find the absolute path in Python

As mentioned at the beginning of this article you can run your Python app on different operating systems, therefore you want to automatically find the full path of the file you wish to import in your code instead of hardcoding it.

So given a path such as «src/examplefile.txt» , how do you find the file’s absolute path relative to the current working directory ( /Users/dannysteenman/home/projects/example-project/ ) in Python?

To get the absolute path in Python you write the following code:

import os os.path.abspath("src/examplefile.txt")

To explain the Python code: first, you have to import the os module in Python so you can run operating system functionalities in your code.

Читайте также:  Java start thread already started

Then you use the os.path library to return a normalized absolutized version of the pathname path.

This will result in the following output:

/Users/dannysteenman/home/projects/example-project/src/examplefile.txt

Conclusion

As you can see an absolute path helps you find the full path of a file or directory relative to the current working directory. This is useful since you get the flexibility to find files or folders and return the correct path on different operating systems.

To get an absolute path in Python you use the os.path.abspath library. Insert your file name and it will return the full path relative from the working directory including the file.

If you need guidance on finding a relative path in Python, read the following article below.

Источник

Как получить каталог текущих файлов сценариев на 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.

Источник

Оцените статью