如何使用python将gzip文件中的字符串替换为另一个字符串?

2024-10-01 00:26:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在gzip中找到特定的字符串,用另一个字符串替换它并更新gzip文件。在

这是我的python脚本。在

import gzip
import string

lines = gzip.open("PhoneWindowManager.java.gz", "rb")
definition = "name="+'"setHdmiPlugged"'+"/>"
print definition   
for line in lines:    
    if definition in line:
        before = ">"+"setHdmiPlugged"+"</a>"
        print before
        after = " title="+'"Join"'+"><font color="+'"red"'">"+"setHdmiPlugged"+"</font></a>"
        print after
        new_str = string.replace(line, before, after)
        print new_str
        **** How can I update the gzip file with the new_str? ****
        break

如何替换特定的字符串并写入它?在

实际上我想用超链接标题和红色来更新方法定义的html标记

以前

^{pr2}$

之后

<a class="l" name="5132" href="#5132">5132</a>    <b>void</b> <a class="xmt" name="setHdmiPlugged"/><a href="/source/s?refs=setHdmiPlugged&amp;project=android" class="xmt" title="Test"><font color="red">setHdmiPlugged</font></a>(<b>boolean</b> <a class="xa" name="plugged"/><a href="/source/s?refs=plugged&amp;project=android" class="xa">plugged</a>) {

编辑

我完成了这个代码。如有需要,请参考以下代码。在

import gzip
import string
import os

os.rename("PhoneWindowManager.java.gz","PhoneWindowManager_orig.java.gz")
input = gzip.open("PhoneWindowManager_orig.java.gz", "rb")
output = gzip.open("PhoneWindowManager.java.gz", "wb")
definition = "name="+'"setHdmiPlugged"'+"/>"

for line in input:    
    if definition in line:            
        before = ">"+"setHdmiPlugged"+"</a>"        
        after = " title="+'"Join"'+"><font color="+'"red"'">"+"setHdmiPlugged"+"</font></a>"
        new_str = string.replace(line, before, after)
        output.write(new_str)
    else:     
        output.write(line)

input.close()
output.close()

Tags: nameimportnewlinejavaclassfontgz