Find a file in python

0 votes
I have a file that may be in a different place on each user's machine. How do I implement a search for the file? I need to figure out a way that I can pass the file's name and the directory tree to search in. Can anyone help me with that?
Mar 27 in Python by ana1504.k
• 6,110 points
13 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes
you can use os.walk in the following way:

import os

def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)
 

And this will find all matches:

def find_all(name, path):
    result = []
    for root, dirs, files in os.walk(path):
        if name in files:
            result.append(os.path.join(root, name))
    return result
 

And this will match a pattern:

import os, fnmatch
def find(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result

find('*.txt', '/path/to/dir')
answered Mar 27 by SDeb
• 9,660 points

Related Questions In Python

0 votes
1 answer

How to find the value of a row in a csv file in python?

If you want to find the value ...READ MORE

answered 3 days ago in Python by Sanam
8 views
+3 votes
7 answers

How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

answered Mar 31, 2018 in Python by DareDev
• 6,520 points
55 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,420 points
42 views
0 votes
2 answers

Extracting data from a JSON file in Python

Here is what i found and was ...READ MORE

answered Nov 27, 2018 in Python by Rupali
3,983 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
22 views
0 votes
1 answer

In Python, how do I read a file line-by-line into a list?

with open(fname) as f:     content = f.readlines() # you ...READ MORE

answered Oct 9, 2018 in Python by SDeb
• 9,660 points
62 views
0 votes
1 answer

Is there a string 'contains' in python?

In this case, you can use the ...READ MORE

answered Sep 25, 2018 in Python by SDeb
• 9,660 points
45 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.