0

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?

5
  • 1
    It should give you absolute path , though for relative paths it would consider the path being relative to current directory. Can you give example of the issue you are seeing? Commented Oct 9, 2015 at 1:47
  • 2
    I think OP is wanting to provide as input "foo.txt" and have it return the absolute path of wherever that file is in the filesystem. Is that correct @I.A.S. Commented Oct 9, 2015 at 1:52
  • You're providing an implied relative path and it's returning the absolute path of that relative path. Can you clarify what your expected results? Commented Oct 9, 2015 at 2:14
  • "os.path.abspath(filename)" Commented Oct 9, 2015 at 5:18
  • It gives back C:/Users/user/Python27/Filename. Commented Oct 9, 2015 at 5:19

1 Answer 1

2

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]] 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks idjaw. Works great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.