简体   繁体   中英

Using a text file with strings and searching for the strings in files in folders

I'm working on searching for strings inside text files. What I have is a CSV file with multiple lines of a single word. Now I need to search files in multiple folders and subfolders for the words in this CSV file. In the end I would like to dump out the results into a text file. The results should have the original word and the result file name that the string was found in. How do you loop through a CSV file with strings while searching files for with these strings? I've only come across individual Python programs that will search for one string in a folder and then print out the results. I've modified one of these to print to a file but am having trouble looping through a CSV search string file.

I suggest the following approach: read the CSV file and create the list of search words. Then create a regular expression out of them, matching any of these words:

regexp = re.compile( '(' + '|'.join(words) + ')' )

Then go through the files using os.walk and apply the regexp to them using re.search .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM