Найти путь до файла python

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.

Читайте также:  Математические знаки на php

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:

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

Читайте также:  Css code to png

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

Источник

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