I am trying to locate the following header in a list of files and replace it with my own.
/*************************************************************************************
* Company: XXX
* File Name: myfile1.c
* Author: MyName
* Date: 30/12/2011
* Operating Environment: XXX
* Compiler with Version Number:
* Description: This file contains an array which returns a structure having API characteristics.
* Version:
***********************************************************************************/
Basically I'm trying to write a python program to traverse a list of directories and do the string replacement in all of files. Following is the code for my program:
import sys
import os
import re
correctlicheader = r'''
/* <MY-HEADER>
*
*/
'''
def changelic():
startdir = sys.argv[1]
for root, dirs, files in os.walk(startdir):
for file in files:
actualfilename = os.path.join(root, file)
print("Reading file: %s" %(actualfilename))
f = open(actualfilename, 'r')
read_data = f.read()
#try replacing the incorrect header
p = re.compile("<MY-REGULAREXPRESSION-HERE>")
changed_data = p.sub(correctlicheader, read_data, 1)
f.close()
f= open(actualfilename, 'w')
f.write(changed_data)
f.close()
print("End")
if __name__ == '__main__':
changelic()
The problem is not getting 'MY-REGULAREXPRESSION-HERE' right. I tried
p = re.compile("/\*[\*]*\r\n[ *[a-zA-Z0-9:/\.]+\r\n]*\*/")
and various permutations of the above. But I keep getting
matched = p.match(read_data)
None
Any suggestions to replace 'MY-REGULAREXPRESSION-HERE'? Also, is there any better method to do the same without open(read-mode)-close-open(write-mode)-write ?
/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/works in my test of your code. I hope the code is backed up or under source control.