我有一个文件内容是以下:在
He is good at python.
Python is not a language as well as animal.
Look for python near you.
Hello World it's great to be here.
现在,脚本应该搜索模式“python”或“pyt”或“pyth”或“python”或任何与“p/python”相关的regex。在“特别的狮子”之后加上新的单词。所以输出应该变成以下:在
^{pr2}$我怎么能做到呢?在
在注:- 直到现在我写的代码这:在
def insertAfterText(args):
file_name = args.insertAfterText[0]
pattern = args.insertAfterText[1]
val = args.insertAfterText[2]
fh = fileinput.input(file_name,inplace=True)
for line in fh:
replacement=val+line
line=re.sub(pattern,replacement,line)
sys.stdout.write(line)
fh.close()
你最好写一个新的文件,而不是试图写到一个现有文件的中间。在
with open
是打开文件的最佳方式,因为一旦完成,它会为您安全可靠地关闭文件。下面是一种使用with open
同时打开两个文件的酷方法:在这里,我们打开现有文件,并打开一个新文件(创建它)以写入。我们循环输入文件,并简单地将每一行写入新文件。如果原始文件中的一行包含正则表达式模式的匹配项,那么在写入原始行之后,我们还将写入
Lion\n
(包括新行)。在将文件读入变量:
使用regex并将结果写回:
^{pr2}$编辑: 要从命令行insert使用:
并替换
与
在open()中,将“textfile”改为textfile。在
相关问题 更多 >
编程相关推荐