![](/img/trans.png)
[英]How to search for word in text file and print the entire line with Python?
[英]How to search a word in a file and replace the entire line with a new line?
我有一個文件(帶有extension.hgx),其中包含一些數據,如下所示:
length = 0.00000783
height = 48
RATIO = 2
X = 1.0
Y = 1.0
我想打開文件並替換兩行:
height = 48
RATIO = 2
帶有:
height = 8
RATIO = 8
我嘗試解析該文件,並可以搜索“高度”和“比率”。 不幸的是,我無法用新行替換該行並重新保存文件。 在我的情況下,問題是文件中參數的值(例如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
這無助於替換完整行並再次保存文件。 返回空文件。任何幫助將不勝感激。
問候,里斯
這個怎么樣?
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')
您需要在找到“高度”行后在第一個循環中停止迭代:
if line.find(search_phrase) >= 0:
print line_num
break
我建議使用正則表達式工具:
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()
無論您以什么順序將新行添加到文件中(這就是為什么我在示例中的“ height”行之前寫了“ RATIO”行)
該程序設法獲得字典dic ,該字典dic用於創建正則表達式,該正則表達式允許搜索要替換的行並將其替換為dic中記錄的行,作為與該行的名字相對應的值
“ sdjlkhbfvjhdbfjhsdoijhfsdhfksdhfh”行不重要。 我將其放在新的位置以表明regex regx僅與“名稱=某物”格式的行匹配
此代碼應按原樣工作。 您只需要給filename指定一個文件名即可; 如果有任何錯誤,請提供。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.