Абсолютный путь до папки python

Текущая директория в Python

Как в Python — программе узнать путь до текущей директории со скриптом. Я знаю, что для этого требуется библиотека os, но там столько различных классов и функций, что можно пол дня убить на поиски.

5 ответов 5

Если вы запускаете скрипт C:\Scripts\script.py из D:\work папки:

D:\work> py C:\Scripts\script.py 
  • D:\work — это текущая рабочая директория на момент старта скрипта. open(‘file.txt’) будет пытаться открыть D:\work\file.txt файл
  • C:\Scripts — это директория со скриптом.

Текущая рабочая директория

Текущая рабочая директория возвращается os.getcwd() функцией, где CWD это Current Working Directory («текущая рабочая директория»). os.getcwdb() возвращает путь в виде байт. Происхождение функции от POSIX getcwd(3) . Другие способы могут вернуть разные результаты в зависимости от настроек доступа промежуточных директорий, общей длины (от платформы зависит) итд—не изобретайте своих способов, если не осознаёте всех последствий возможного изменения в поведении функции. Также нетрадиционные способы получения рабочей директории могут ухудшить читаемость другими Питон-программистами. Из The Zen of Python :

There should be one— and preferably only one —obvious way to do it.

По умолчанию относительные пути используют именно эту директорию, поэтому явно вызывать os.getcwd() редко нужно. Например, open(‘file.txt’) вызов открывает файл ‘file.txt’ в текущей директории. Если необходимо передать полный путь в виде строки, то можно использовать os.path.abspath(‘file.txt’) — getcwd() снова явно не используется.

Path.cwd() из pathlib модуля возвращает путь к текущей директории как объект c разными полезными и удобными методами такими как .glob(‘**/*.py’) .

Директория со скриптом

Текущая рабочая директория может отличаться от директории с текущим Питон-скриптом. Часто, но не всегда можно os.path.dirname(os.path.abspath(__file__)) использовать, чтобы получить директорию с текущим Питон скриптом, но это не всегда работает. Посмотрите на get_script_dir() функцию, которая поддерживает более общий случай.

Если хочется получить данные из файла, расположенного относительно установленного Питон-модуля, то используйте pkgutil.get_data() или setuptools’ pkg_resources.resource_string() вместо построения путей c помощью __file__ . Это работает даже, если ваш пакет упакован в архив. В Python 3.7 появился importlib.resources модуль. К примеру, если у вас есть Питон пакет data внутри которого лежит файл.txt , то чтобы достать текст:

import importlib.resources text = importlib.resources.read_text('data', 'файл.txt') 

Если вы хотите найти место куда пользовательские данные можно положить, то appdirs модуль предоставляет переносимый способ:

import appdirs # $ pip install appdirs user_data_dir = appdirs.user_data_dir("Название приложения", "Кто создал") 

Разные платформы (Windows, MacOS, Linux) используют разные соглашения, appdirs позволяет не плодить сущностей и использовать на каждой платформе подходящие директории.

Читайте также:  Приведение типов данных php

Источник

How do I get the full path of the current file’s directory? [duplicate]

__file__ is not defined when you run python as an interactive shell. The first piece of code in your question looks like it’s from an interactive shell, but would actually produce a NameError , at least on python 2.7.3, but others too I guess.

Why. is. this. so. hard. There are like a dozen SO threads on this topic. Python: «Simple is better than complex. There should be one— and preferably only one —obvious way to do it.»

@eric it isn’t hard, and the existence of multiple questions isn’t evidence of something being hard — it’s evidence of people not doing good research, of question titles being suboptimal for SEO, and/or of people failing to close duplicates that should be closed.

12 Answers 12

The special variable __file__ contains the path to the current file. From that we can get the directory using either pathlib or the os.path module.

Python 3

For the directory of the script being run:

import pathlib pathlib.Path(__file__).parent.resolve() 

For the current working directory:

import pathlib pathlib.Path().resolve() 

Python 2 and 3

For the directory of the script being run:

import os os.path.dirname(os.path.abspath(__file__)) 

If you mean the current working directory:

import os os.path.abspath(os.getcwd()) 

Note that before and after file is two underscores, not just one.

Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of «current file». The above answer assumes the most common scenario of running a python script that is in a file.

Читайте также:  Javascript add cell to table

References

abspath() is mandatory if you do not want to discover weird behaviours on windows, where dirname(file) may return an empty string!

@DrBailey: no, there’s nothing special about ActivePython. __file__ (note that it’s two underscores on either side of the word) is a standard part of python. It’s not available in C-based modules, for example, but it should always be available in a python script.

@cph2117: this will only work if you run it in a script. There is no __file__ if running from an interactive prompt. \

Using Path from pathlib is the recommended way since Python 3:

from pathlib import Path print("File Path:", Path(__file__).absolute()) print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__ 

Note: If using Jupyter Notebook, __file__ doesn’t return expected value, so Path().absolute() has to be used.

That is correct @YellowPillow, Path(__file__) gets you the file. .parent gets you one level above ie the containing directory. You can add more .parent to that to go up as many directories as you require.

Sorry I should’ve have made this clearer, but if Path().absolute() exists in some module located at path/to/module and you’re calling the module from some script located at path/to/script then would return path/to/script instead of path/to/module

Path(__file__) doesn’t always work, for example, it doesn’t work in Jupyter Notebook. Path().absolute() solves that problem.

from pathlib import Path path = Path(__file__).parent.absolute() 
  • Path(__file__) is the path to the current file.
  • .parent gives you the directory the file is in.
  • .absolute() gives you the full absolute path to it.

Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path) .

This should be the accepted answer as of 2019. One thing could be mentioned in the answer as well: one can immediately call .open() on such a Path object as in with Path(__file__).parent.joinpath(‘some_file.txt’).open() as f:

Читайте также:  Php file put contents перенос строки

The other issue with some of the answers (like the one from Ron Kalian, if I’m not mistaken), is that it will give you the current directory, not necessarily the file path.

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

Sorry but this answer is incorrect, the correct one is the one made by Bryan `dirname(abspath(file)). See comments for details.

I found the following commands return the full path of the parent directory of a Python 3 script.

Python 3 Script:

#!/usr/bin/env python3 # -*- coding: utf-8 -*- from pathlib import Path #Get the absolute path of a Python3.6 and above script. dir1 = Path().resolve() #Make the path absolute, resolving any symlinks. dir2 = Path().absolute() #See @RonKalian answer dir3 = Path(__file__).parent.absolute() #See @Arminius answer dir4 = Path(__file__).parent print(f'dir1=\ndir2=\ndir3=\ndir4=') 
  1. dir1 and dir2 works only when running a script located in the current working directory, but will break in any other case.
  2. Given that Path(__file__).is_absolute() is True , the use of the .absolute() method in dir3 appears redundant.
  3. The shortest command that works is dir4.

A bare Path() does not provide the script/module directory. It is equivalent to Path(‘.’) – the current working directory. This is equivalent only when running a script located in the current working directory, but will break in any other case.

USEFUL PATH PROPERTIES IN PYTHON:

from pathlib import Path #Returns the path of the current directory mypath = Path().absolute() print('Absolute path : <>'.format(mypath)) #if you want to go to any other file inside the subdirectories of the directory path got from above method filePath = mypath/'data'/'fuel_econ.csv' print('File path : <>'.format(filePath)) #To check if file present in that directory or Not isfileExist = filePath.exists() print('isfileExist : <>'.format(isfileExist)) #To check if the path is a directory or a File isadirectory = filePath.is_dir() print('isadirectory : <>'.format(isadirectory)) #To get the extension of the file fileExtension = mypath/'data'/'fuel_econ.csv' print('File extension : <>'.format(filePath.suffix)) 

OUTPUT: ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED

Absolute path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2

File path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2\data\fuel_econ.csv

Источник

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