Jason Schayer
Jason Schayer

Reputation: 171

return text file path

I want to return the path of a file, If it is found by the program, but I want it to continue to loop(or recursively repeat) the program until all files are checked.

def findAll(fname, path):
for item in os.listdir(path):
    n = os.path.join(path, item)
    try:
        findAll(n, fname)
    except:
        if item == fname:
            print(os.idontknow(item))

So I'm having trouble with calling the path, right now I have

os.idontknow(item) 

as a place holder

Input is :

findAll('fileA.txt', 'testpath')

The output is:

['testpat\\fileA.txt', 'testpath\\folder1\\folder11\\fileA.txt','testpath\\folder2\\fileA.txt']

Upvotes: 0

Views: 567

Answers (2)

RocketDonkey
RocketDonkey

Reputation: 37279

Per my comment above, here is an example that will start at the current directory and search through all sub-directories, looking for files matching fname:

import os

# path is your starting point - everything under it will be searched
path = os.getcwd()    
fname = 'file1.txt'
my_files = []

# Start iterating, and anytime we see a file that matches fname,
# add to our list    
for root, dirs, files in os.walk(path):
  for name in files:
    if name == fname:
      # root here is the path to the file
      my_files.append(os.path.join(root, name))

print my_files

Or as a function (more appropriate for your case :) ):

import os

def findAll(fname, start_dir=os.getcwd()):
  my_files = []
  for root, dirs, files in os.walk(start_dir):
    for name in files:
      if name == fname:
        my_files.append(os.path.join(root, name))
  return my_files


print findAll('file1.txt')
print findAll('file1.txt', '/some/other/starting/directory')

Upvotes: 2

verbsintransit
verbsintransit

Reputation: 908

Something like this, maybe?

import os
path = "path/to/your/dir"
for (path, dirs, files) in os.walk(path):
    print files

Upvotes: 1

Related Questions