Since my machine is installed with Python 3.4, I have not tested that. For matching the file name name in python you can use fnmatch module.I will provide you a sample code from the documentation. The Python 3.5 added a feature for recursive lookup with glob.glob.The module "pathlib" was added only in the Python 3.4.Solution 3 - use "pathlib" # lookup in current dir apps/library/migrations/0001_initial.py Pythonic_files = fnmatch.filter(filenames, pattern) Variant 2.2 - Lookup recursive # lookup recursiveįor dirpath, dirnames, filenames in os.walk(path): In : fnmatch.filter(os.listdir(path), pattern) Variant 2.1 - Lookup in current dir # lookup in current dirįnmatch.filter(os.listdir(path), pattern) 9 Answers Sorted by: 334 os.walk is the answer, this will find the first match: import os def find (name, path): for root, dirs, files in os.walk (path): if name in files: return os.path. Solution 1 - use "glob" # lookup in current dir For example if you accidentally convert a string to a list and end up checking against all the characters of a string, you could end up getting a slew of false positives.īut it's better to have a problem that's easy to fix than a solution that's hard to understand. The only thing about this design is that it doesn't protect you against making the mistake of passing a string instead of a list. It may be hard for novice python programmers to really get used to using list comprehensions for filtering, and it can have some memory overhead for very large data sets, but for listing a directory and other simple string filtering tasks, list comprehensions lead to more clean documentable code. I prefer this form of list comprehensions because it reads well in English.įor each fn in os.listdir for my path, give me only the ones that match any one of my included extensions. For example: In D:\Samplefile\file.txt I need to find 'hello world' and in D:\Samplefile\file1.txt I. I have many such files in the samplefile directory,where in which I need to find specific words in that file. If any(fn.endswith(ext) for ext in included_extensions)] For ex: I am in C:\python\ directory, I want to search a pattern in a file which is located in D drive. Included_extensions = įile_names = [fn for fn in os.listdir(relevant_path)
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |