How to Get an Absolute File Path in Python

How to get an absolute file path in Python

>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

Also works if it is already an absolute path:

>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

Get absolute path of file in python

Ok, so your problem hasn't got anything to do with absolute paths. The problem is that you're trying to open a file that exists in another directory using only it's filename. Use os.path.join to create the complete file name and use that:

for fname in listing:
full_name = os.path.join(directory, fname)
with open(full_name) as f:
if "yes" in f.read():
print f.name

How do I get the full path of the current file's directory?

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.

References

  1. pathlib in the python documentation.
  2. os.path - Python 2.7, os.path - Python 3
  3. os.getcwd - Python 2.7, os.getcwd - Python 3
  4. what does the __file__ variable mean/do?

Python: How to get the absolute path of file where a function was called?

You can use module traceback to get access to the call stack. The last element of the call stack is the most recently called function. The second last element is the caller of the most recently called function.

foo.py:

import traceback
def foo():
stack = traceback.extract_stack()
print(stack[-2].filename)

bar.py:

import foo
foo.foo()

On the prompt:

import bar
# /path/to/bar.py

How to get the absolute path of the imported python file

Try the following code:

import os
os.path.abspath(config)

edit-1 (credits: Milan Cermak)

Add the following code in config.py


import os

def get_path():
return os.path.abspath(__file__)


Related Topics



Leave a reply



Submit