[英]How to search a word in a file and replace the entire line with a new line?
I have a file (with extension.hgx) that has some data like this: 我有一个文件(带有extension.hgx),其中包含一些数据,如下所示:
length = 0.00000783
height = 48
RATIO = 2
X = 1.0
Y = 1.0
I would like to open the file and replace the two lines: 我想打开文件并替换两行:
height = 48
RATIO = 2
With: 带有:
height = 8
RATIO = 8
I tried parsing the file and could search for the "height" and "RATIO". 我尝试解析该文件,并可以搜索“高度”和“比率”。 Unfortunately, I could not replace the line with new line and re-save the file. 不幸的是,我无法用新行替换该行并重新保存文件。 In my case the problem is that, that in the file the value of parameters eg height(=48) varies and sometimes has uneven spaces in between. 在我的情况下,问题是文件中参数的值(例如height(= 48))变化,并且有时它们之间的间隔不均匀。 I want to replace this complete line with-- height = 8 我想用-height = 8代替这条完整的线
I have written the following code 我写了下面的代码
import fileinput
import sys
f = open('test.hgx','r')
line_num = 0
search_phrase = "height"
for line in f.readlines():
line_num += 1
if line.find(search_phrase) >= 0:
print line_num
newline='height = 8'
lnum=1
for line in fileinput.FileInput("test.hgx",inplace=1):
if lnum==line_num:
result = newline+"\n"
else:
result=line
lnum=lnum+1
sys.stdout.write(result)
print line
This does not help replace complete line and save the file again. 这无助于替换完整行并再次保存文件。 returns empty file.Any help would be greatly appreciated. 返回空文件。任何帮助将不胜感激。
Regards, Ris 问候,里斯
How's this? 这个怎么样?
with open('test.hgx') as f: lines = f.read().splitlines()
with open('test.hgx', 'w') as f:
for line in lines:
if line.startswith('height') or line.startswith('RATIO'):
f.write(line.rsplit(' ', 1)[0] + ' 8\n')
else:
f.write(line + '\n')
you need to stop iterating in the first loop after finding the "height" line: 您需要在找到“高度”行后在第一个循环中停止迭代:
if line.find(search_phrase) >= 0:
print line_num
break
I propose to use regex tool: 我建议使用正则表达式工具:
import re
regx = re.compile('^(([^ \t]+)[ \t]+=.+)',re.MULTILINE)
new = '''\
RATIO = 8
sdjlkhbfvjhdbfjhsdoijhfsdhfksdhfh
height = 8
'''
dic = dict(mat.group(2,1) for mat in regx.finditer(new))
regchange = re.compile('^('+'|'.join(dic.iterkeys())+')[ \t]+=[^\r\n]+',re.MULTILINE)
with open(filename,'r+') as f:
content = f.read()
f.seek(0,0)
f.write(regchange.sub(lambda m: dic[m.group(1)],content))
f.truncate()
You put in new the lines you want to take place in the file, no matter in which order (that's why I wrote 'RATIO' line before 'height' line in my exemple, to show) 无论您以什么顺序将新行添加到文件中(这就是为什么我在示例中的“ height”行之前写了“ RATIO”行)
The program manages to obtain the dictionary dic that is used to create the regex that allows to search for the lines to be replaced and to substitute them with lines recorded in dic as values corresponding to the first name of the line 该程序设法获得字典dic ,该字典dic用于创建正则表达式,该正则表达式允许搜索要替换的行并将其替换为dic中记录的行,作为与该行的名字相对应的值
The line 'sdjlkhbfvjhdbfjhsdoijhfsdhfksdhfh' has no importance. “ sdjlkhbfvjhdbfjhsdoijhfsdhfksdhfh”行不重要。 I put it in new to show that the regex regx matches only with lines of the format 'name = something' 我将其放在新的位置以表明regex regx仅与“名称=某物”格式的行匹配
This code should work as-is. 此代码应按原样工作。 You have just to give a file's name to filename ; 您只需要给filename指定一个文件名即可; If any error, give it please. 如果有任何错误,请提供。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.