I have multiple files that I'm iterating through and for each file I check if a pattern exists there or not and the pattern can either exist once or multiple times or it doesn't exist at all. I want to edit the line that has the pattern once the pattern is found and rewrite the line with the pattern only. If the pattern is not there then I close the file without any modifications. My code:
for root, dirs, files in os.walk('C:/Users/Documents/'):
for fname in files:
for line in fileinput.input(os.path.join(root, fname), inplace = 1):
if re.search(r"([\w-d])", line):
x=re.sub(r"([\w-d])", r"(\1).", line)
print line.replace(line,x)
The problem is it changes the pattern fine when it finds it but for the files that doesn't have the pattern it deletes their contents completely. And if the pattern exists in multiple lines, it keeps one line only and deletes the rest. What am I missing?
EDIT
I'm flexible also to use "open"
or any other method that can solve my problem. My main concern is I don't want to rewrite the lines in files that don't have the pattern. For tracking purposes I want to only modify the files that has the pattern. so far my research online [1] [2][3] shows that I can either write to a temp file and use it later as original file or read all the lines and then write all of them again regardless if the file has the pattern or not. is there a better way of solving this problem?