Find a file

Karim kliateni at gmail.com
Fri Jul 1 01:11:11 EDT 2016



On 01/07/2016 02:51, tdsperth at gmail.com wrote:
> Hi All
>
> I have a web app that allows me to choose a file - the file name is returned but I need
> to find the path to the file so I can add it as an attachment to a email.
>
> The files I am returning could be in different folders/directories.
>
> Thanks for any help.
>
> Cheers
>
> Colin
>
Hello,

I did this almost equivalent unix find command in python it is 
documented, it is a generator. If it could help you:

import os
from os.path import join as jp, normpath as np

def find(dirs, filenames=None, exts=None, exclude_dirs=None, 
exclude_filenames=None, followlinks=False):
     """ Equivalent to the unix/linux find shell command.

     @param dirs                the top directories where to search. 
Could be a simple string.
                                Default to current directory '.'.

     @param filenames           the searched file names. Could be a 
simple string.

     @param exts                an additional parameter to search files 
by its extension.
                                Could be cumulative with the filenames

     @param exclude_dirs        a filter to exclude given top 
directories from the search process.
                                Coud be a simple string.

     @param exclude_filenames   a filter to bypass certain files by its 
name.
                                Useful when using a search by file 
extension.
                                Could be a simple string.

     @param followlinks         a boolean to specify whether to follow
                                symbolic links to subdirectories. 
Defaulted to False.


     @return a generator data which provides the found file one after 
another.
     """
     if not filenames and not exts:
         raise ValueError('The list of searched files and the list of 
searched file extensions could not be both empty!')

     if filenames is None:
         filenames         = ''
     if exts is None:
         exts              = ''
     if exclude_dirs is None:
         exclude_dirs      = ''
     if exclude_filenames is None:
         exclude_filenames =  ''

     # Default value
     if not dirs:
         dirs = tuple(('.',))

     if isinstance(dirs, str):
         dirs              = tuple((dirs,))
     if isinstance(filenames, str):
         filenames         = tuple((filenames,))
     if isinstance(exts, str):
         exts              = tuple((exts,))
     if isinstance(exclude_dirs, str):
         exclude_dirs      = tuple((exclude_dirs,))
     if isinstance(exclude_filenames, str):
         exclude_filenames = tuple((exclude_filenames,))

     # The search.
     for d in dirs:
         for dirpath, dirnames, fnames in os.walk(d, 
followlinks=followlinks):
             # Filtering unwanted top directories.
             for d in exclude_dirs:
                 if d in dirnames:
                     dirnames.remove(d)
             # Search for file names or extensions
             for f in fnames:
                 file_extension = os.path.splitext(f)[-1][1:] # 
extension without the dot!
                 if f in filenames or (file_extension in exts and f not 
in exclude_filenames):
                     yield jp(dirpath, f)


if __name__ == '__main__':
    #print(np('\n'.join(find(dirs='.', exts='li', 
exclude_filenames='cds.li'))))
    # Test
    l = tuple(find(dirs='.', filenames='cds.lib'))

    print('\n'.join(l))

Cheers
Karim



More information about the Python-list mailing list