2011-05-06 34 views
0

我有了這樣一些數據的文件(extension.hgx):如何搜索文件中的單詞並將整行替換爲新行?

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

我想打開該文件,並替換兩行:


height    = 48 
RATIO    = 2 

With:


height    = 8 
RATIO    = 8 

我試着解析文件,並可以搜索「高度」和「比率」。不幸的是,我無法用新行替換該行並重新保存該文件。在我的情況下,問題是,在文件中,參數的值例如高度(= 48)變化,有時在兩者之間有不均勻的空間。我想更換這個完整的線with-- 高度= 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 

這不利於更換整條生產線,並再次保存文件。返回空文件。任何幫助將不勝感激。

問候, R2爲

回答

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

感謝你的作品就像一個魅力! – user741592 2011-05-06 14:38:14

1

您需要停止在尋找「身高」行後的第一個迭代循環:

if line.find(search_phrase) >= 0: 
    print line_num 
    break 
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() 

你把行要發生的文件中,無論以何種順序(這就是爲什麼我寫了「RATIO 'line before'height'line in my example,to show)

該程序設法獲取字典dic用於創建允許搜索要替換的行的正則表達式,以及到與記錄在DIC作爲對應於線

線「sdjlkhbfvjhdbfjhsdoijhfsdhfksdhfh」沒有重要性的第一名字值的行代替它們。我把它放在新的位置來顯示正則表達式regx僅與'name = something'格式的行匹配

此代碼應該按原樣工作。您只需將文件名稱設爲;文件名稱爲;如果有任何錯誤,請給它。

相關問題