匹配模式后将新行添加到文件-Python

时间:2018-11-28 12:09:45

标签: python-3.x

我有一个名为'file.txt'的文件,其内容如下。

 [Jack]
 sv0f3fj3jff0j


 [Tom]
 343767y6y6y5yu

我必须在每个名称之后添加新行(通过读取用户名作为输入)。谁能帮帮我吗 ?我尝试使用以下步骤,但没有成功。

#!/usr/bin/python36

inv_file = '/root/file.txt'
cn_search = input("\nEnter the name: ")
new_line = input("\nEnter the new line : ")
with open(inv_file) as in_file:
     buf = in_file.readlines()
     print(buf.replace('[').replace(']'))
with open(inv_file, "w") as in_file:
     for line in buf:
         if line.startswith('[') and line.endswith(']'):
            mod_line = line.replace('[', '').replace(']', '')
            if mod_line == cn_search:    
               buf  = buf + "\n" + new_ip_ex
               out_file.write(buf)

1 个答案:

答案 0 :(得分:2)

先读取然后重写文件是正确的,但是您也可以更改括号,这是不必要的。这样做:

import re

with open(inv_file) as in_file:
    old_contents = in_file.readlines()

with open(inv_file, 'w') as in_file:
    for line in old_contents:
        in_file.write(line)
        if re.search(r'\[.*\]', line):
             in_file.write('YOUR MESSAGE HERE\n')