1

I've made a simple script which finds my file test.txt, but I am trying to make it return the location of the file. It only returns whether it found the file, but I am struggling to make the function return the file path of the specified file(s), I would like it to return a list of file paths if more than one test.txt was found.

Code:

import os

wallet = 'test.txt'
filepath = 'C:\\'

def search():
    for root,dirs,files in os.walk(filepath):
        if wallet in files:
            return 'File found'
        else:
            return 'Nope.. not here'
print search() 
0

2 Answers 2

1

Use os.path.join to join your file name with the root and return it as a string:

import os

wallet = 'test.txt'
filepath = r'C:\\'

def search():
    for root,dirs,files in os.walk(filepath):
        if wallet in files:
            return os.path.join(root, wallet)
        else:
            return 'Nope.. not here'
print(search())

If it finds your file, this should print:

C:\path_to_file\test.txt

PS: I see you're using Windows, if you give the path as '/' it will have the same result and provide working paths, with the upside of being compatible with Unix as well.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but what do you put the r before the 'C:\\'?
Python will read in your string as C:\ instead of C:\\, creating the string with r'' ensures that Python reads it in as a raw (the meaning of the r) string: C:\\. But in this case either way will work, because Python is smart enough to equate the two when attempting to open your file. In fact, the paths it returns will only have the one \, like I originally gave as an example.
0

Try this:

$ cat walk
#!/usr/local/cpython-3.3/bin/python

import os

wallet = 'stdio.h'
filepath = '/usr'

def search():
    for root, dirs, files in os.walk(filepath):
        if wallet in files:
            yield os.path.join(root, wallet)

print(list(search()))

zareason-dstromberg:~/src/outside-questions/walk x86_64-pc-linux-gnu 13799 - above cmd done 2014 Wed Mar 19 12:16 PM

$ ./walk
['/usr/include/stdio.h', '/usr/include/x86_64-linux-gnu/bits/stdio.h', '/usr/include/c++/4.7/tr1/stdio.h']

It should work in 2.x or 3.x; tested with 3.3.

Comments

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.