Original address: http://blog.csdn.net/xsckernel/article/details/9007517
As a result of the transfer of an arm project under ads to the GNU project, a lot of repetitive changes are needed, such as
[Plain]View Plaincopyprint?
- ABC EQU 1
Modified to:
[Plain]View Plaincopyprint?
- #define ABC 1
If a manual modification is a waste of time, so the Python script to do the work, found that it is easy to do (previously encountered similar problems are always written in C code, the amount of code and error prone!!) )
The source code is as follows:
[Python]View Plaincopyprint?
- def func ():
- Ffrom=open ("2440init.s","R")
- Fto=open ("2440init1.s","W")
- while True:
- L = Ffrom.readline ()
- if not L:
- Break
- if ' EQU ' in L:
- temp = L.split ("EQU")
- Temp1 = ' #define ' + temp[0] + temp[1]
- #print Temp1
- Fto.write (TEMP1)
- Else:
- Temp1 = L
- Fto.write (TEMP1)
- if __name__ = = "__main__":
- Func ()
Use a file 2440init.s to test:
[Plain]View Plaincopyprint?
- ABC EQU 1
- PDS EQU 9
The resulting file 2440init1.s content is as follows:
[Plain]View Plaincopyprint?
- #define ABC 1
- #define PDS 9
The first thing that's said is to replace the contents of the file Ffrom with FTO Open should be the same file, but found that the write file output stream opened, will automatically empty the file (except append mode) looks like Java performance.
Can be done with the following code
[Python]View Plaincopyprint?
- def func ():
- input = open ("2440init.s")
- lines = Input.readlines ()
- Input.close ()
- Output = open ("2440init.s",' W ');
- For line in lines:
- #print Line
- if not line:
- Break
- if ' EQU ' in line:
- temp = Line.split ("EQU")
- Temp1 = ' #define ' + temp[0] + temp[1]
- Output.write (TEMP1)
- Else:
- Output.write (line)
- Output.close ()
- if __name__ = = "__main__":
- Func ()
If you have a larger project file, you need to traverse every file in the project. If the file contains the specified string, such as #include "appdef.h", replace it with #include "datatype.h":
[Python]View Plaincopyprint?
- Import OS
- Def direc ():
- For D,FD,FL in os.walk ('/home/shichao/gun-ucos '):
- For F in FL:
- Sufix = Os.path.splitext (f) [1][1:]
- if ((Sufix = = ' h ') or (Sufix = = ' C ')):
- #print Sufix
- Func (d + '/' + f)
- def func (filename):
- input = open (filename)
- lines = Input.readlines ()
- Input.close ()
- Output = open (filename,' W ')
- For line in lines:
- if not line:
- Break
- if ((' appdef.h ' line ) and (' include ') :
- temp = Line.split ("Appdef")
- Temp1 = temp[0] + ' datatype ' + temp[1]
- Output.write (TEMP1)
- Else:
- Output.write (line)
- Output.close ()
- if __name__ = = "__main__":
- Direc ()
"Go" using Python to modify the contents of a file