我有文本是由'='分隔的鍵值對。如果密鑰匹配,我想替換該行。如果沒有,我想將其附加在底部。我嘗試了幾種方法,其中包括:如果找到或附加替換行 - 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)
任何人都可以看到這個問題嗎?
您能否提供您的輸入樣本? – silel