开发者

How to search a word in a file and replace the entire line with a new line?

开发者 https://www.devze.com 2023-03-04 14:43 出处:网络
I have a file (with extension.hgx) that has some data like this: length=0.00000783 height=48 RATIO=2 X=1.0

I have a file (with extension.hgx) that has some data like this:

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 e.g. height(=48) varies and sometimes has uneven spaces in between. I want to replace this complete line with-- 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 appreciate开发者_开发百科d.

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)

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

The line 'sdjlkhbfvjhdbfjhsdoijhfsdhfksdhfh' has no importance. I put it in new to show that the regex regx matches only with lines of the format 'name = something'

This code should work as-is. You have just to give a file's name to filename; If any error, give it please.

0

精彩评论

暂无评论...
验证码 换一张
取 消