By using below code, I copy the file content from CONFIG.txt
to CONFIG_shorted.txt
by using shutil.copy
. After that, trying to find the search keywords (pattern
) in CONFIG_shorted.txt and replace with Short names (Shorted_Dir_Name_List
). but line is not getting replaced, instead new lines are added at end of the file CONFIG_shorted.txt with \t \n characters, how to avoid special symbols?
for root, dirs, files in os.walk('.'):
for i in files:
if i == 'CONFIG.txt':
old_name = os.path.join(root, i)
#base, extension = os.path.splitext(i)
new_name = os.path.join(root, 'CONFIG_shorted.txt')
if not os.path.exists(new_name):
shutil.copy(old_name, new_name)
f = open(new_name, 'r+')
with f as myFile:
for line in enumerate(myFile):
for j in range(len(Dir_Name_List)):
pattern = "/" + Dir_Name_List[j] + "/"
if pattern in str(line):
line = str(line).replace(pattern, "/" + Shorted_Dir_Name_List[j] + "/")
f.write(str(line))
f.close()
For your reference:
Dir_Name_List[]
= 'Source_Library', 'STD_Lib'
Shorted_Dir_Name_List[]
= 'S_L', 'STD_L'
CONFIG.txt:
{
"precompile_headers": [
"${ROOT}/Source_Library/STD_Lib/a.h",
"${ROOT}/Source_Library/STD_Lib/a.c"
]
}
Output i'm getting is: CONFIG_shorted.txt
{
"precompile_headers": [
"${ROOT}/Source_Library/STD_Lib/a.h",
"${ROOT}/Source_Library/STD_Lib/a.c"
]
}(0, '{\n')(1, '\n')(2, '\t\t\t\t"precompile_headers": [\n')(3, '\t\t\t\t\t"${ROOT}/S_L/STD_L/a.h",\n')(4, '\t\t\t\t\t"${ROOT}/S_L/STD_L/a.c",\n')(5, '\t\t\t\t]\n')(6, '}\n')
Expected output is: CONFIG_shorted.txt
{
"precompile_headers": [
"${ROOT}/S_L/STD_L/a.h",
"${ROOT}/S_L/STD_L/a.c"
]
}