user1469433
user1469433

Reputation: 1

Traversing a directory and returning text in python

Does anyone have code to traverse a directory and sub directory while searching for a text value? Then once found return the values in python?

Upvotes: 0

Views: 122

Answers (3)

Rodrigue
Rodrigue

Reputation: 3687

First, os.walk() returns a Python generator that traverses a given directory tree. For each directory encountered in the tree, the generator returns a 3-tuple of (dirpath, dirnames, filenames). You will need to use os.walk() inside a loop

Then, the built-in open() function is used to return a file object from which you can read the content of the file. read() will read the full content of the file, while readlines() will read one line at a time.

Assuming that the text you are looking for cannot be on multiple lines so that it is safe to process your files one line at a time, you could do something along these lines:

import os
import re

matching_files = []

root = "/path/to/root/folder/you/want/to/walk"
# Navigate the directory structure starting at root
for root, dirs, files in os.walk(root):
    # For each file in the current directory
    for file_name in files:
        # Reconstruct the full path
        file_path = os.path.join(root, file_name)
        # Open the file
        with open(file_path, 'r') as f:
            # Read the file one line at a time
            for line in f.readlines():
                 # Look for your text in the current line
                 if re.findall(r'text_you_are_searching_for', line):
                     matching_files.append(file_path)

You can get more details in the online docs about

Upvotes: 1

PinkElephantsOnParade
PinkElephantsOnParade

Reputation: 6592

To implement your own grep you can use os.walk() and some basic file I/O. We need more information on what specifically is required before we can produce code.

Upvotes: 0

unwind
unwind

Reputation: 399949

Just read the documentation for os.walk(), give it a try, and come back if you can't make it work.

Upvotes: 1

Related Questions