Created
December 8, 2016 09:32
-
-
Save henryscala/03bdfbd0a6fd4964409909f3d5f7c815 to your computer and use it in GitHub Desktop.
a script to walk a dir, and filter each line of the files in that dir, and do something if the line fulfills some criteria
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# a script to walk a dir, and filter each line of the files in that dir, and do something if the line fulfills some criteria | |
import os | |
import os.path | |
script_dir = r"<script-dir>" | |
dir_to_walk = r"<dir-to-walk>" | |
os.getcwd() | |
os.chdir(script_dir) | |
os.getcwd() | |
classes_file_name = os.path.join(script_dir, "<somefile.txt>" ) | |
with open(classes_file_name) as file: | |
content = file.read() | |
#print(content) | |
classes = content.split("\n") | |
classes = [cls.strip() for cls in classes] # remove leading/trailing white spaces | |
#print(len(classes)) | |
def line_with_words(line, words): | |
for word in words: | |
if line.find(word) >= 0 : | |
return True | |
return False | |
def handle_dir(adir): | |
print("handling dir",adir) | |
files = os.listdir(adir) | |
java_files = [file for file in files if file.endswith(".java")] | |
folders = [folder for folder in files if os.path.isdir(os.path.join(adir,folder))] | |
for java_file in java_files: | |
full_path = os.path.join(adir, java_file) | |
with open(full_path,"rb") as file: | |
content = file.read() | |
print("handling file", java_file) | |
lines = content.splitlines() | |
#print("lines",lines) | |
with open(full_path,mode="wb") as file: | |
for line in lines: | |
#print("line:",line) | |
linestr = line.decode("utf-8") | |
if line_with_words(linestr, classes) and line_with_words(linestr,["get","set"]) and line_with_words(linestr,["public"]): | |
line += b"henrychange" | |
file.write(line) | |
file.write(b"\n") | |
#recursive call | |
for folder in folders: | |
handle_dir(os.path.join(adir,folder) ) | |
#break #temp process one file only | |
handle_dir(dir_to_walk) | |
print("done.") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment