我是python的初学者,我被困在给我的作业中。我有一个名为file.h的文件,它有一定的信息和数字介于这两者之间。
Working copy:C:/tmp
Repository root:svn:/localhost
VERSION_REV 8797
Schedule:normal
Date:13/12/2010
我需要编写一个python代码,这样每当我运行它时,应该搜索数字8797并将其替换为存储在我的变量中的数字,即x = 8798.我试过如下,但没有成功。
fout = open("path to\file\file.h","r+")
for line in open("path to\file\file.h"):
line = line.replace("VERSION_REV %i","x")
fout.write(line)
fout.close()
抱歉,我忘了提及我使用的是Windows7系统。
答案 0 :(得分:0)
试试这个......
import re
data = open("path to\file\file.h","r+").read()
re.sub(r'VERSION_REV [0-9]+', 'VERSION_REV ' + newstr, data)
open("path to\file\file.h","w").write(data)
没有重新
fout = open("path to\file\file.h","r+")
for line in open("path to\file\file.h"):
if "VERSION_REV" in line:
line = "VERSION_REV " + newstr
fout.write(line)
fout.close()
答案 1 :(得分:0)
您可以使用re.sub
import re
.....
line = re.sub(r'(?<=VERSION_REV )\d+', x, line)
答案 2 :(得分:0)
查看以下代码..这对我有用。
fout=open("c:\path to file\file.h", "r+")
for line in open("c:\path to file\file.h"):
if "VERSION_REV" in line:
line = "VERSION_REV " + "" + x + '\n' #where 'x' has new version _rev 8798
fout.write(line)
fout.close()