3
def replace(file_path, pattern, subst):
   file_path = os.path.abspath(file_path)
   #Create temp file
   fh, abs_path = mkstemp()
   new_file = open(abs_path,'w')
   old_file = open(file_path)
   for line in old_file:
       new_file.write(line.replace(pattern, subst))
   #close temp file
   new_file.close()
   close(fh)
   old_file.close()
   #Remove original file
   remove(file_path)
   #Move new file
   move(abs_path, file_path)

我有这个函数来替换文件中的字符串。但我想不出一个好方法来替换找到模式的整行。

例如,如果我想使用模式“John”替换包含:“John work hard all day”的行,替换为“Mike did not work so hard”。

使用我当前的功能,我必须以模式编写整行来替换整行。

4

1 回答 1

7

首先,您可以更改此部分:

for line in old_file:
    new_file.write(line.replace(pattern, subst))

进入这个:

for line in old_file:
    if pattern in line:
        new_file.write(subst)
    else:
        new_file.write(line)

或者你可以让它更漂亮:

for line in old_file:
    new_file.write(subst if pattern in line else line)
于 2013-10-21T13:15:29.977 回答