I.A.S.
I.A.S.

Reputation: 81

Finding File Path in Python

I'd like to find the full path of any given file, but when I tried to use

os.path.abspath("file")

it would only give me the file location as being in the directory where the program is running. Does anyone know why this is or how I can get the true path of the file?

Upvotes: 0

Views: 103

Answers (1)

idjaw
idjaw

Reputation: 26570

What you are looking to accomplish here is ultimately a search on your filesystem. This does not work out too well, because it is extremely likely you might have multiple files of the same name, so you aren't going to know with certainty whether the first match you get is in fact the file that you want.

I will give you an example of how you can start yourself off with something simple that will allow you traverse through directories to be able to search.

You will have to give some kind of base path to be able to initiate the search that has to be made for the path where this file resides. Keep in mind that the more broad you are, the more expensive your searching is going to be.

You can do this with the os.walk method.

Here is a simple example of using os.walk. What this does is collect all your file paths with matching filenames

Using os.walk

from os import walk
from os.path import join

d = 'some_file.txt'
paths = []
for i in walk('/some/base_path'):
    if d in i[2]:
        paths.append(join(i[0], d))

So, for each iteration over os.walk you are going to get a tuple that holds:

(path, directories, files)

So that is why I am checking against location i[2] to look at files. Then I join with i[0], which is the path, to put together the full filepath name.

Finally, you can actually put the above code all in to one line and do:

paths = [join(i[0], d) for i in walk('/some/base_path') if d in i[2]] 

Upvotes: 2

Related Questions