Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using terminal command to search through files for a specific string within a python script

I have a parent directory, and I'd like to go through that directory and grab each file with a specific string for editing in python. I have been using grep -r 'string' filepath in terminal, but I want to be able to do everything using python. I'm hoping to get all the files into an array and go through each of them to edit them.

Is there a way to do this by only running a python script?

like image 852
BlazeRunner738 Avatar asked Mar 27 '26 12:03

BlazeRunner738


1 Answers

changing current folder to parent

import os    
os.chdir("..")

changing folder

import os
os.chdir(dir_of_your_choice)

finding files with a rule in the current folder

import glob
import os
current_dir = os.getcwd()
for f in glob.glob('*string*'):
    do_things(f)
like image 64
Massimo Variolo Avatar answered Mar 29 '26 03:03

Massimo Variolo