开发者

Replace Multiple lines in Jython

I have written a small program to replace a set of characters , but i also want two or more replace command in a single program .

Apart from it i also want to add an bracket after random set of characters.

This is my Program

file_read=open('<%=odiRef.getOption("READ")%>/EXPORT.XML','r')
file_write=open('<%=odiRef.getOption("READ")%>/EXPORT_1.XML','w')
count_record=file_read.read()
while count_record :
    s=count_record.replace('<Field name="ExeDb"type="java.lang.String"><![CDATA[S]]></Field>','<Field name="ExeDb" type="java.lang.String"><![CDATA[W]]></Field>')
    file_write.write(s)
    t=count_record.replace('<Field name="Txt" type="java.lang.String"><![CDATA[','<Field name="Txt" type="java.lang.String"><![CDATA[TRIM(')
    file_write.write(t)
    count_record=file_read.read()
    print s
file_read.close()
file_write.close()

As you can see when i try to do with read line i get two lines in the final file.

1) I want both the replace command to work but with only single file.

2) Also is there is any way to read and write in a single file , i dont know why r+ was not working properly.

3) I also want to modify the line

t=count_record.replace('<Field name="Txt" type="java.lang.String"><![CDATA[','<Field name="Txt" type="java.lang.String"><![CDATA[TRIM(')

to somethings like

t=count_record.replace('<Field name="Txt" type="java.lang.String"><![CDATA[','<Field name="Txt开发者_如何学运维" type="java.lang.String"><![CDATA[TRIM($$$) ')

where $$$ represents words or character present in the source File.

in short adding ) close bracket at the end , irrespective of any number of words or character after opening bracket .

Thanks so much for all your help.


This is wrong on many levels - you can not simultaneously read and write from the same file, file.read() command reads entire contents, and you dont have to save after each replace. Something like this:

file = open('myfile', 'r+')
contents = file.read()
file.seek(0) # rewind    
file.write(contents.replace('something', 'else').replace('and this too', 'replaced'))

Comment code is garbled, including here... You need to replace that using regular expressions. See module "re" description, you basically need something like this:

import re
contents = re.sub(
  '<Field name="Txt" type="java.lang.String"><!\[CDATA\[TRIM\(([^)]*)\]\]></Field>', 
  '<Field name="Txt" type="java.lang.String"><![CDATA[TRIM(\1)]]></Field>', 
  contents
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜