-1

I want to find the complete path of a file (name is user input) within a computer. I tried os.path.dirname(filename) and os.path.abspath(filename), but all it does is return the path of the file added to the current working directory.

For example, let IntelGFX.txt be a file with path C:\Intel\Logs\IntelGFX, but the path I get on using os.path.abspath('IntelGFX') is C:\Python34\IntelGFX.

So how do I get the original path of the file?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Son_Goku
  • 27
  • 3
  • Please don't roll back legitimate edits - we make them for a reason (in this case: 1. to fix the formatting; and 2. The first paragraph and *"THANKS!!"* were just pointless noise). – jonrsharpe Jul 14 '15 at 13:19
  • @jonrsharpe it seems i misunderstood the meaning of rollback. I thought rollback would edit my version of the question and present your edited version as the final question. – Son_Goku Jul 14 '15 at 13:22
  • No, *exactly the opposite*; it removed my edit and restored your original version. As a user with >2k rep my edits don't go into the review queue, which may be what you're confusing this with. – jonrsharpe Jul 14 '15 at 13:23
  • ohh, my mistake then. Thanks for the help. – Son_Goku Jul 14 '15 at 13:44

2 Answers2

1

So you want to search the filesystem for a file with the given name? This will not be quick, depending on the number of files you have to search through.

You might like to try using os.walk. You can use it to walk over all the files from a given root directory. In the following I use it to find all the directories called "tests" in my python install location.

import os
from os.path import join, getsize
from itertools import chain

target = "tests"
path = "c:\\Python34"

found = []
for root, dirs, files in os.walk(path):
    for name in chain(files, dirs):
        if name == target:
            found.append(join(root, name))

print(found)
Dunes
  • 37,291
  • 7
  • 81
  • 97
0

all [abspath] does is return the path of the file added to the current working directory

Well, according to the documentation:

On most platforms, [abspath] is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).

so this is the expected behaviour. Think about it - where should Python be looking if you just give it a filename? You can't just expect it to start searching everywhere for it!

If that's the behaviour you want, you will need to implement it explicitly; see e.g. Find a file in python.

Community
  • 1
  • 1
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437