如果找到或追加替换行 - python

时间:2017-04-12 21:06:27

标签: 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)

有人能看到这个问题吗?

3 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分:1)

我强烈建议您阅读有关如何read and write files

的python文档

如果您以写入模式open(path, 'w')打开现有文件,其内容将被删除:

  

模式可以是(...)' w'仅用于写入(将删除具有相同名称的现有文件)

要替换python中的一行,您可以查看: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)

请注意,上面的代码匹配键的每个行(key = blob或blob = key)都将被替换。