2017-04-12 10 views
1

我有文本是由'='分隔的鍵值對。如果密鑰匹配,我想替換該行。如果沒有,我想將其附加在底部。我嘗試了幾種方法,其中包括:如果找到或附加替換行 - python

def split_command_key_and_value(command): 
    if '=' in command: 
     command2 = command.split('=') 
     return command2 

def test(command, path): 
    command2 = split_command_key_and_value(command) 
    pattern = command2[0] 
    myfile = open(path,'r') # open file handle for read 
# use r'', you don't need to replace '\' with '/' 
    result = open(path, 'w') # open file handle for write 
    for line in myfile: 
     line = line.strip() # it's always a good behave to strip what you read from files 
     if pattern in line: 
     line = command # if match, replace line 
     result.write(line) # write every line 
    myfile.close() # don't forget to close file handle 
    result.close() 

我知道上面的僅僅是替換文本,但它刪除了文件中的文本,我不明白爲什麼。有人能指出我正確的方向嗎?

感謝

更新:

我幾乎沒有,但我的一些線路也有類似的按鍵,所以多發線匹配時,只有1個應該。我試圖在我的循環中併入一個正則表達式邊界,但沒有運氣。我的代碼如下。有沒有人有建議?

文件中有一些不是鍵值的文本,所以我想跳過它。

def modify(self, name, value): 
     comb = name + ' ' + '=' + ' ' + value + '\n' 
     with open('/file/', 'w') as tmpstream: 
     with open('/file/', 'r') as stream: 
      for line in stream: 
       if setting_name in line: 
        tmpstream.write(comb) 
       else: 
        tmpstream.write(line) 

我想我明白了。見下面的代碼。

def modify(self, name, value): 
     comb = name + ' ' + '=' + ' ' + value + '\n' 
     mylist = [] 
     with open('/file/', 'w') as tmpstream: 
     with open('/file/', 'r') as stream: 
      for line in stream: 
       a = line.split() 
       b = re.compile('\\b'+name+'\\b') 
       if len(a) > 0: 
        if b.search(a[0]): 
        tmpstream.write(comb) 
        else: 
        tmpstream.write(line) 

我說得太快了。它停在我提供的關鍵值。所以,它只寫一行,不寫不匹配的行。

def modify(name, value): 
    comb = name + ' ' + '=' + ' ' + value + '\n' 
    mylist = [] 
    with open('/file1', 'w') as tmpstream: 
     with open('/file2', 'r') as stream: 
     for line in stream: 
      a = line.split() 
      b = re.compile('\\b'+name+'\\b') 
      if len(a) > 0: 
       if b.search(a[0]): 
        tmpstream.write(comb) 
      else: 
       tmpstream.write(line) 

任何人都可以看到這個問題嗎?

+0

您能否提供您的輸入樣本? – silel

回答

1

因爲當你打開文件進行寫入

result = open(path, 'w') # open file handle for write 

你只是刪除它的內容。嘗試寫入不同的文件,完成所有工作後,用新文件替換舊文件。或者將所有數據讀入內存,然後處理並寫入文件。

with open(path) as f: 
    data = f.read() 
with open(path, 'w') as f: 
    for l in data: 
     # make job here 
1

首先你正在閱讀的寫同一個文件...的 你可以先讀這一切,並通過寫入線

with open(path,'r') as f: 
    myfile = f.read() # read everything in the variable "myfile" 
result = open(path, 'w') # open file handle for write 
for line in myfile.splitlines(): # process the original file content 1 line at a time 
    # as before 
1

我強烈建議對如何閱讀Python文檔read and write files

如果你打開寫模式open(path, 'w')現有的文件,其內容將被刪除:

模式可以是(...)「w」表示只寫(已有的文件具有相同名稱將被刪除)

要更換蟒蛇一條線,你可以看看這個:Search and replace a line in a file in Python

這裏是一個提供的解決方案也適用於您的上下文(測試python3):

from tempfile import mkstemp 
from shutil import move 
from os import close 

def test(filepath, command): 
    # Split command into key/value 
    key, _ = command.split('=') 
    matched_key = False 

    # Create a temporary file 
    fh, tmp_absolute_path = mkstemp() 

    with open(tmp_absolute_path, 'w') as tmp_stream: 
     with open(filepath, 'r') as stream: 
      for line in stream: 
       if key in line: 
        matched_key = True 
        tmp_stream.write(command + '\n') 
       else: 
        tmp_stream.write(line) 

     if not matched_key: 
      tmp_stream.write(command + '\n') 

    close(fh) 
    move(tmp_absolute_path, filepath) 

注意,與上文線匹配密鑰(密鑰=斑點或斑塊=鍵)的代碼將被替換。

相關問題