2

Using File Explorer in Windows, we can find files by typing part of the file names in the Search box. With the Advance option, we even can find a file according to its content.

Is it possible to search Python files based on their content without "manually opening each file and viewing it in a viewer or editor program"? I use Jupyter Lab to create Python files.

For example, I want to find python files that contain dayfirst.

Thanks for help.

k.ko3n
  • 954
  • 8
  • 26
  • 1
    That sounds quite possible. But please clarify what you mean by "without opening the files". As in, without manually opening each file and viewing it in a viewer or editor program? Also, do you have any code yet or are you just asking in general? If so then this question is probably going to get closed for being too broad since you haven't really shown any effort. – Random Davis Apr 23 '19 at 15:22
  • @RandomDavis. Yes, the question has been editied using your sentence. This is a general question. I am curious if Python have that capability without needing a code as WIndows File Explorer does. – k.ko3n Apr 23 '19 at 15:24
  • 1
    A little PoweShell could really help: https://stackoverflow.com/questions/8153750/how-to-search-a-string-in-multiple-files-and-return-the-names-of-files-in-powers – Ben Apr 23 '19 at 15:41

2 Answers2

2

To enable content search using Windows Explorer, you can set up your Windows indexing options to include the contents of .py files. Here is a step by step guide:

https://www.howtogeek.com/99406/how-to-search-for-text-inside-of-any-file-using-windows-search/

Screenshot (for a batch file)...

Advanced Search Options

(Also make sure that the location where you keep your .py files is in a location indexed by Windows.)

Martin Stone
  • 12,682
  • 2
  • 39
  • 53
1

Take a look at pathlib.

Relevant points/example:

from pathlib import Path

p = Path('.')

files = [x for x in p.iterdir() if x.is_file()]
found_files = []

for file in files:
    with file.open() as f:
        for line in f:
            if 'dayfirst' in line:
                found_files.append(file)
Sam
  • 541
  • 1
  • 3
  • 10
  • This solution is if you want to find the files using Python. The above answer which indexes .py files is if you want to use Windows Explorer instead. – Sam Apr 23 '19 at 15:56