在一行中搜索一个模式并复制同一行并将其插入该行

时间:2017-07-19 05:32:10

标签: python

如果文件1有4行文本,例如

 I was born in vizag
 I love python
 I am 22 years old
 I am not an experienced programmer

如果这些是4行,如果我搜索的模式是" love", file 2 中的所需输出应该是这样的

 I was born in vizag
 I love python
 I love python
 I am 22 years old
 I am not an experienced programmer

我怎样才能实现它?

这是我尝试但未成功的代码。

import datetime
import os
import fileinput

Dir=input("Source directory:")
os.chdir(Dir)

Filelist=os.listdir()

Filename=input("Enter the file name:")
search=input("Enter a pattern you wish to search for:")
now=datetime.datetime.now()
now_string = str(now.strftime(" %d-%m-%Y_%H%M%S.bak"))
x=Filename
y=now_string
Filename=x
fn=x[:-4]
newname=fn+y

with open (Filename,"r")as input_file, open(newname,"x")as outfile:
    for line in input_file:
        if search in line:
            newline=line.replace(line,line+line)
            outfile.write(newline)

使用此代码将outfile创建为:

I love python
I love python

但其他线路正在消失!

1 个答案:

答案 0 :(得分:0)

尝试这个小改动:

with open (Filename,"r")as input_file, open(newname,"x")as outfile:
    for line in input_file:
        if search in line:
            line=line.replace(line,line+line)
        outfile.write(line)

即使没有"爱"你想写出这条线。在其中 - 在这种情况下只有一次。

更直接的修改:

with open (Filename,"r")as input_file, open(newname,"x")as outfile:
    for line in input_file:
        outfile.write(line)
        if search in line:
            outfile.write(line)

在这里,你真的只需要在需要的时候写一个额外的时间。