发布于2021-10-15 00:14 阅读(369) 评论(0) 点赞(17) 收藏(2)
Hello fellow Pythonistas,
I have a script which searches through all files contained within a single directory for a 'string' keyword. If it finds the 'string' keyword within any of the files, it will print the name of this file to the IDLE command screen. It seems to work quite well. The inputs are gathered by the program using user prompts.Typically I am searching for a single word within a large series of text files.
HOWEVER - Now I want to build on this in two ways 1) I want to modify the code to that it can also search through all the files contained within sub-folders within the specified directory. 2) I would also like to specify that the searches are limited to a certain type of file extension such as .txt.
Can anyone provide some guidance on either of these two enhancements ???
I am using Python 3 and am VERY new to Python (Just started playing with it 2 weeks ago in an attempt to automate some boring searches through my employers folder structures)
Much appreciated to anyone who can provide some help. Cheers, Fraz
# This script will search through all files within a single directory for a single key word # If the script finds the word within any of the files it will print the name of this file to the command line import os print ('When answering questions, do not add a space and use forward slash separators on file paths') print ('') # Variables to be defined by user input user_input = input('Paste the directory you want to search?') directory = os.listdir(user_input) searchstring = input('What word are you trying to find within these files?') for fname in directory: if os.path.isfile(user_input + os.sep + fname): # Full path f = open(user_input + os.sep + fname, 'r') if searchstring in f.read(): print('found string in file "%s"' % fname) f.close()enter code here
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任