Python code to search file




















The program, see. This is equivalent to the grep command in the Linux OS. Here, we will use Python 2. The program expects the string pattern and directory from the user. Let us examine the code and discuss it. This method works in recursive mode. This is the main function of the program which handles all the options. The program offers you six options.

The —m option gives the number of the file and the line. You can use the —h option to get help for all options. Get the see. In this way, see. Use the option —s as in Figure 2. You can see that only file names are returned. Use the option —m as shown in Figure 3. You can see that file names and lines are returned. We can use the for loop to iterate through the list and use the in operator to check whether the string is in the line in every iteration.

If the string is found in the line, it returns True and breaks the loop. If the string is not found after iterating all lines, it returns False eventually. The file read method returns the content of the file as a whole string. The next time, the file will be searched in the dictionary dumped in the pickle file.

Now that you have understood the logic of the program, let us look at the program in detail. I have broken it into different functions. This function gets all the drives in your Windows machine. Our next function is the search1 function, which constructs a dictionary in which the file name is the key and the path is the value of the dictionary. The create function opens the thread process for each drive, and each thread process calls the search1 function.

After creating the dictionary, the following code dumps the dictionary into the hard disk as a pickle file. Next time, when you search any file, the program will search the file in the dumped dictionary, as follows:.

Here, we used the search method of regular expressions so that we can use a regular expression to find the file. The rest of the code is very easy to understand.

Let us save the complete code as finder. Be careful of case sensitivity. JPG in the file system. What about using yield instead of preparing the result list? Please consider updating your answer to Python 3.

Comprehention list can replace the function, e. Show 3 more comments. In Python 3. Path '. Kenyon Kenyon 4 4 silver badges 8 8 bronze badges. Dima Tisnek Dima Tisnek 9, 4 4 gold badges 56 56 silver badges bronze badges.

Specifically, use scandir. Note that if you're using Python 3. Also, PEP is probably a better document to read for info than that issue. This script will avoid following those. Note that this is windows-specific! Random Nerd 1 1 silver badge 9 9 bronze badges.



0コメント

  • 1000 / 1000