# If path does not exist, set search path to current directoryįor fname in os.listdir(path=search_path): If not (search_path.endswith("/") or search_path.endswith("\\") ): # Append a directory separator if not already present Search_str = input("Enter the search string : ") Search_path = input("Enter directory path to search : ") It returns 0 if the string is found and -1 if the string is not found. The find method is passed the required string. A simple find method can be used with the read () method to find the string in the file. The filename, line number, index and the whole line that contains the string is output to the user console. Use find Method to Search a String in a File in Python.
If found, the find method returns index where the string was found. Let this file be SampleFile.txt with the following contents: To replace text in a file we are going to open the file in read-only using the open() function. First, we create a text file in which we want to search and replace text. The find() method is called to check if the search string is present in a line. Let see how we can search and replace text in a text file. The files that match the file type are opened and each line is read in loop. If no file type is input then program will search all files in the directory. ini the program will check if the filename ends with the extension. conf etc., If the user inputs a file type, for example. The file type can be any text file format such as. In the next step, each file in the directory is checked and if it matches the file type. If the path is invalid or if it does not exist then the search path is set to the current directory. If the directory path does not containing a directory separator, which is forward slash (/) in case of Linux and either a backward slash() or forward slash (/) in case if Windows, then it is appended to search path. The user is prompted to enter a directory path, file type and a text string to be searched. The program uses the os module to get the files from a directory. The program outputs the filenames that contain the search string and also the line number and column number where the text appears in the file. Additionally, by entering the file type, the search can be restricted to a subset of the files in the directory. The user inputs the directory path and a text string to search.
This is a Python program to search for a specified text in all files of a directory. Script in python 3.3.2 import os def find (name): count0 for root, dirs, files in os.walk('C:'): if name in files: print (root,name) count+1.