如何在文件中搜索单词并用新行替换整行?

0 投票
3 回答
1164 浏览
提问于 2025-04-16 17:07

我有一个文件(扩展名是.hgx),里面有一些数据,像这样:

length             =  0.00000783
height             =  48
RATIO              =  2
X                  =  1.0
Y                  =  1.0

我想打开这个文件,并替换其中的两行:


height             =  48
RATIO              =  2

替换成:


height             =  8
RATIO              =  8

我尝试解析这个文件,搜索“height”和“RATIO”。可惜的是,我无法用新行替换旧行并重新保存文件。我的问题在于,文件中的参数值,比如height(=48),是会变化的,有时候中间的空格也不一样。我想把整行替换成--
height = 8

我写了以下代码:

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

但是这段代码无法替换整行,也不能重新保存文件,结果是文件变成了空的。任何帮助都非常感谢。

祝好,
Ris

3 个回答

0

我建议使用正则表达式工具:

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

你可以在new里放入你想要在文件中替换的行,顺序无所谓(这就是我在例子中先写'RATIO'行再写'height'行的原因)

这个程序能够生成一个字典dic,这个字典用来创建正则表达式,帮助查找需要替换的行,并用dic中与行名对应的值来替换它们

这一行'sdjlkhbfvjhdbfjhsdoijhfsdhfksdhfh'其实没什么重要性。我把它放在new里只是为了说明正则表达式regx只会匹配格式为'name = something'的行

这段代码应该可以直接使用。你只需要给filename一个文件名;如果有任何错误,请告诉我。

1

你需要在第一个循环中找到“高度”这一行后就停止继续循环。

if line.find(search_phrase) >= 0:
    print line_num
    break
2

这样怎么样?

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')

撰写回答