I have a Python script that searches for and replaces a string contained in all files within a directory. Now I need you to store the rest of that line in a dictionary.
That is, when I find this line:
ORIGIN("ab_220_ABBC2x_5_ABBC2x_OriginDestiny:
1..............................\n");
My script converts it into the following, replacing the name of the function:
RESULT("ab_220_ABBC2x_5_ABBC2x_OriginDestiny:
1..............................\n");
But now I need to store the following in a dictionary:
"ab_220_ABBC2x_5_ABBC2x_OriginDestiny:
1 .............................. \ n "'
Example:
dictionary = {'valor1': 'ab_220_ABBC2x_5_ABBC2x_OriginDestiny:
1..............................\n'}
That is, to take out the content between ( ... );
.
This is read from a directory that contains .cc and .h files where the lines I look for are of this style:
ORIGIN("ab_220_ABBC2x_5_ABBC2x_OriginDestiny:
1..............................\n");
ORIGIN("ab_220_ABBC2x_: 3..............................\n");
That is, they are C ++ files that have a function with a name that I want to replace (I already do that with my script) but I also want to save what that function receives, what is between ( ... );
The result would be that the name of the function will be replaced in the file:
DESTINY("ab_220_ABBC2x_5_ABBC2x_OriginDestiny: ...1 \n");
DESTINY("ab_220_ABBC2x_: 3" , value);
And it will store what happens to the function in a dictionary, in this case:
dict = { '1' : 'ab_220_ABBC2x_5_ABBC2x_OriginDestiny: ...1' ,
'2': 'ab_220_ABBC2x_: 3" , value' }
My script:
import re
import os
import shutil
import sys
drc = ''
backup = '/path/bk'
pattern = re.compile('ORIGIN')
oldstr = 'ORIGIN'
newstr = 'DESTINY'
if os.path.exists(sys.argv[1]):
drc = os.path.abspath(sys.argv[1])
else:
print("Cannot find directory: " + sys.argv[1])
exit()
for dirpath, dirname, filename in os.walk(drc): #Obtiene una lista de las rutas.
for fname in filename:
path = os.path.join(dirpath, fname) #Une la ruta con el nombre del archivo.
strg = open(path).read() #Abre los archivos para sólo lectura.
if re.search(pattern, strg): #Si encuentra el patrón
shutil.copy2(path, backup) #Crear una copia de seguridad.
strg = strg.replace(oldstr, newstr) #Reemplaza.
f = open(path, 'w') #Abre los archivos en modo escritura.
f.write(strg) #Escribe los cambios.
f.close() #Cierra los archivos.