[Solved] Need to delete if block in file using python


The issue you are hitting here is that .readlines() reads line separated by a newline escape character (\n) and treats them as separate entries in an array – so your data contains:

data == ['if (aaaaa == b) {\n', 'qqqq\n', 'cccc\n', 'vvv\n', '}'] 

If something isn’t working, run it through a debugger or print it to console to what the variable actually contains.

Try converting that array to a single string, then replacing the newline characters and feeding that your regex expression.

with open(file_path) as f:       
    data = f.readlines() 
      
print(data)
mod_data = "".join(data).replace("\n", "")
print(mod_data)

Alternatively, use f.read() to just read a file in as a single string.

Edited:

You can try it this way and rework your regex expression.

import re

file_path = "test2.py" 

with open(file_path, "r") as f: 
    data = f.readlines() 

data = "".join(data).replace("\n", "")
data = re.sub(r'if\s\(aaaaa == b\)\s\{.*?\}', 'this is a replacement', data, flags=re.DOTALL)
print(data)

with open(file_path, 'w') as f:   
    f.write(data)

2

solved Need to delete if block in file using python