Dragos Iorgulescu's website | cvtech blogthoughtsbandcampgithub
home \ hlog \ "Finding files with Python"
Written on  

Just another entry in my Python-related scrapbook :). There are many occasions when having some code snippets related to file searches can prove useful.

Find for the first occurrence of a given filename in a given directory:

import os def findFile(fileName, pathToSearch): for root, directories, files in os.walk(pathToSearch): if fileName in files: return os.path.join(root, fileName)

Find all files matching a given pattern and return a vector (list) with all entries (not that elegant yet, but it'll do for the moment):

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

« Una despre disciplină Discard content from a text file (with Python) »

Valid CSS! HTML5 Valid Donate using PayPal
GDPR Info | Built with Jekyll | Hosted on GitHub Pages with FreeDNS.afraid.org | Subscribe via RSS