![]() Other comparisons you could do are item.lower().endswith('.txt') or some other string comparison. If re.compile('.*lowda.*').search(item): # Here you can do your own comparisonįilename = (curr_dir + os.p + item)Ĭurr_dir = os.path.abspath(curr_dir + os.p + os.pardir) # Loop through parent directories until you hit the end or find a match fnmatchcase () can be used to perform a case-sensitive comparison, regardless of whether that’s standard for the operating system. Both parameters are case-normalized using os.path.normcase (). ![]() This article helps you find out many of the functions in one place which gives you a brief knowledge about how to list all the files of a certain type in a directory by using Python programming. Test whether the filename string matches the pattern string, returning True or False. ![]() These functions are present in different modules such as os, glob, etc. Starting_dir = 'C:\\Users\\AvasaralaC\\Documents\\Projects' If youre on Python 3.5+, you can use pathlibs glob() instead of the glob module alone. In python, there are several built-in modules and methods for file handling. Import re # only if you want to use regex # Looking for a file with the string 'lowda' in it (like beltalowda or inyalowda) I'm using regex but a basic string compare would work fine too. Approach: We can use the re. It returns a list of strings in the matching order when scanning the string from left to right. And you can change how the match is found. The re.findall (pattern, string) method scans string from left to right, searching for all non-overlapping matches of the pattern. It doesn't require changing the working directory and it has a place for you to do something when you find a match. import os userinput input ('What is the name of your directory') directory os.listdir (userinput) searchstring input ('What word are you trying to find') for fname in directory: if os.path.isfile (userinput + os.sep + fname): Full path f open (userinput + os.sep + fname, 'r') if searchstring in f.read (): print ('found st. I wanted to search backwards through parent directories until I hit the drive root.īumming some inspiration from previous answers, below is what I am using. I was looking for this too, since os.walk is exactly the opposite of what I wanted.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |