您的位置:首页 > 编程语言 > Python开发

【转】使用python 修改文件内容

2014-10-24 11:49 489 查看
原文地址:/article/1897837.html

由于在一个把ads下的arm 工程项目移植到gnu项目时候需要做大量重复的修改,比如把

[plain] view plaincopyprint?

ABC EQU 1

修改为:

[plain] view plaincopyprint?

#define ABC 1

如果用手工一个个修改很浪费时间,所以就用python脚本来做这些工作,发现很容易就搞定了(以前遇到类似问题总是用c代码来写,代码量很多而且容易出错!!)

源代码如下:

[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()

用一个文件 2440init.s 来测试下:

[plain] view plaincopyprint?

abc EQU 1

pds EQU 9

最终生成的文件2440init1.s 内容如下所示:

[plain] view plaincopyprint?

#define abc 1

#define pds 9

前面既然说了是替换文件的内容 ffrom 跟 fto 打开的应该是同一个文件,但是发现 写文件输出流打开后,会自动清空文件(append模式除外) 貌似和java表现一样的。

可以用如下代码完成

[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()

如果一个比较大的工程文件,需要遍历工程中的每一个文件。如果文件中包含指定的字符串比如说 #include "appdef.h" 则将之替换为 #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' in line) and ('include' in line) ):

temp = line.split("appdef")

temp1 = temp[0] + 'datatype' + temp[1]

output.write(temp1)

else:

output.write(line)

output.close()

if __name__ == "__main__":

direc()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: