Python 在文件中搜索一个数字,并在程序运行时替换该数字
我是python的初学者,我被交给我的作业困住了。我有一个名为file.h的文件,其中包含特定的信息,中间有一个类似这样的数字Python 在文件中搜索一个数字,并在程序运行时替换该数字,python,python-2.7,Python,Python 2.7,我是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
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系统。试试这个
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()
你可以用
重新导入
.....
line=re.sub(r’(?检查下面的代码..它确实对我有用
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()
假设您在Unix上,为什么不直接使用命令行?sed-i“s/VERSION\u REV[0-9]*/VERSION\u REV 8979/g”
file另外,只是一个快速响应,它不起作用的原因是replace
不是正则表达式替换,也不是其他智能替换。它只是用第二个参数替换第一个参数的发生率。
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()