If I have a file test.py that resides in some directory, how can I find out from test.py what directory it is in? os.path.curdir will give the current directory but not the directory where the file lives. If I invoke test.py from some directory foo, os.curdir will return foo but not the path of test.py.
thanks.
Here's how to get the directory of the current file:
import os
os.path.abspath(os.path.dirname(__file__))
the answer is to use:
__file__
which returns a relative path.
os.path.abspath(__file__)
can be used to get the full path.
The answers so far have correctly pointed you to os.path.abspath, which does exactly the job you requested. However don't forget that os.path.normpath and os.path.realpath can also be very useful in this kind of tasks (to normalize representation, and remove symbolic links, respectively) in many cases (whether your specific use case falls among these "many" is impossible to tell from the scant info we have, of course;-).
import os
dirname, filename = os.path.split(os.path.abspath(__file__))
os.path has lots of tools for dealing with paths and getting information about paths.
Particularly, you want:
os.path.abspath
Related
I tried every method, but it simply doesn't work. I have a file that is within a subdirectory and that subdirectory lies within a directory. Calling something like
os.path.abspath(__file__))
only yields
directory\\file
but I need
directory\\subdirectory\\file
There should be an easy way to do this, right? I have no idea why abspath doesn't recognize the subdirectory.
from pathlib import Path
my_path = Path("my_file.txt")
full_path = Path.resolve()
Then you can convert full_path to a string if you need it as such.
You should look at the pathlib module
I am trying to get the absolute path of a file, but it's not working. My Code is only showing the path to the directory of my running code. This are the two way I have tried:
1)
import os
print(os.path.abspath("More_Types.py"))
2)
import os
print(os.path.realpath("More_Types.py"))
But I continue to get the full path to my running program. How can I get the correct path to file, that is located some where else in my Computer?
PS: I am sorry I can't provide the output because it will reveal all the folders to my running program.
More_Types.py, subdir/More_Types.py and ../More_Types.py are relative paths.
Outcome
If you provide a relative path, realpath and abspath will return an absolute path relative to the current working directory. So essentially, they behave like os.path.join with the current working directory as first argument:
>>> import os.path
>>> os.path.join(os.getcwd(), 'More_Types.py') == os.path.abspath('More_Types.py')
True
This explains, why you get the result you explained.
Explanation
The purpose of abspath is to convert a relative path into an absolute path:
>>> os.path.abspath('More_Types.py')
'/home/meisterluk/More_Types.py'
Unlike abspath, relpath also follows symbolic links. Technically, this is dangerous and can get you caught up in infinite loops (if a link points to any of its parent directories):
>>> os.path.abspath('More_Types.py')
'/net/disk-user/m/meisterluk/More_Types.py'
Proposed solution
However, if you want to retrieve the absolute path relative to some other directory, you can use os.path.join directly:
>>> directory = '/home/foo'
>>> os.path.join(directory, 'More_Types.py')
'/home/foo/More_Types.py'
>>>
I think the best answer to your question is: You need to specify the directory the file is in. Then you can use os.path.join to create an absolute filepath.
You could use this if you want:
import os
a='MoreTypes.py'
for root , dirs , files in os.walk('.') :
for file in files:
if file==a:
print(os.path.join(root,file))
I am trying to access a text file in the parent directory,
Eg : python script is in codeSrc & the text file is in mainFolder.
script path:
G:\mainFolder\codeSrc\fun.py
desired file path:
G:\mainFolder\foo.txt
I am currently using this syntax with python 2.7x,
import os
filename = os.path.dirname(os.getcwd())+"\\foo.txt"
Although this works fine, is there a better (prettier :P) way to do this?
While your example works, it is maybe not the nicest, neither is mine, probably. Anyhow, os.path.dirname() is probably meant for strings where the final part is already a filename. It uses os.path.split(), which provides an empty string if the path end with a slash. So this potentially can go wrong. Moreover, as you are already using os.path, I'd also use it to join paths, which then becomes even platform independent. I'd write
os.path.join( os.getcwd(), '..', 'foo.txt' )
...and concerning the readability of the code, here (as in the post using the environ module) it becomes evident immediately that you go one level up.
To get a path to a file in the parent directory of the current script you can do:
import os
file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'foo.txt')
You can try this
import environ
environ.Path() - 1 + 'foo.txt'
to get the parent dir the below code will help you:
import os
os.path.abspath(os.path.join('..', os.getcwd()))
For reference. The absolute path is the full path to some place on your computer. The relative path is the path to some file with respect to your current working directory (PWD). For example:
Absolute path:
C:/users/admin/docs/stuff.txt
If my PWD is C:/users/admin/, then the relative path to stuff.txt would be: docs/stuff.txt
Note, PWD + relative path = absolute path.
Cool, awesome. Now, I wrote some scripts which check if a file exists.
os.chdir("C:/users/admin/docs")
os.path.exists("stuff.txt")
This returns TRUE if stuff.txt exists and it works.
Now, instead if I write,
os.path.exists("C:/users/admin/docs/stuff.txt")
This also returns TRUE.
Is there a definite time when we need to use one over the other? Is there a methodology for how python looks for paths? Does it try one first then the other?
Thanks!
If you don't know where the user will be executing the script from, it is best to compute the absolute path on the user's system using os and __file__.
__file__ is a global variable set on every Python script that returns the relative path to the *.py file that contains it.
import os
my_absolute_dirpath = os.path.abspath(os.path.dirname(__file__))
The biggest consideration is probably portability. If you move your code to a different computer and you need to access some other file, where will that other file be? If it will be in the same location relative to your program, use a relative address. If it will be in the same absolute location, use an absolute address.
Probably a simple query.. But basically, I have data in directory "/foo/bar/foobar.txt"
and I am working in directory "/some/path/read_foobar.py"..
Now I want to read the file "foobar.txt" but rather than giving full path, I thought of adding /foo/bar/ to the path..
So, added the following at the start of read_foobar.py
import sys
sys.path.append("/foo/bar")
But when I try to read open("foobar.txt","r"), it is not able to find the file?
how do I do this?
Thanks
You can do it like this:
import os
os.chdir('/foo/bar')
f = open('foobar.txt', 'r')
sys.path is used to set the path used to look for python modules. Short of you writing some helper function that has a list of directories to search in when opening a file, I don't believe there is a standard module that provides this functionality.
From what I gathered from here and some quick tests, appending a path to sys.path will make python search in that path when you import a file/module, but not when open-ing it. Let's say we have a file called foo.py in /foo/bar/
import sys
sys.path.append("/foo/bar/")
try:
f = open('foo.py', 'r')
except:
print('this did not work') # this will print
import foo # no problems here
Unfortunately you can't. The PATH environment variable is only used by the operating system to search for executable files, and python uses it (along with the environment variable PYTHONPATH) to search for python modules to import.
You may want to consider setting a symbolic link to that file from your current working directory
ln -s /foo/bar/foobar.txt /some/path/foobar.text