从头开始写文件

时间:2012-12-19 20:33:39

标签: python python-2.x

我正在编写我的第一个服务器脚本来查找和删除恶意软件js-code,但我找不到一个简单的方法来从头开始重写现有文件,而不是最后。

# -*- coding: utf-8 -*-

import os
import re
import codecs

for dirname, dirnames, filenames in os.walk('.'):
    for filename in filenames:
        f = open(os.path.join(dirname, filename), 'r+b')
        text=f.read()
        if re.search('function g\(\).*\n.*\<script src=\"http://linkfooter.org/linkfooter.js\"></script>\'\);}', text) and os.path.join(filename) != "bezr.py":
            print "starting with " + os.path.join(filename)
            match = re.compile('function g\(\).*\n.*\<script src=\"http://linkfooter.org/linkfooter.js\"></script>\'\);}')
            s = match.sub('', text)
            f.write(s)
        f.close()
        #else:
            #print "in " + os.path.join(dirname, filename) + " none"    
            #f.close()

2 个答案:

答案 0 :(得分:5)

在你写作之前

f.seek(0)f.truncate()之后切断任何额外的文字。

答案 1 :(得分:1)

filepath = os.path.join(dirname, filename)
text = file.read(filepath)
if re.search('function g\(\).*\n.*\<script src=\"http://linkfooter.org/linkfooter.js\"></script>\'\);}', line) and os.path.join(filename) != "bezr.py":
    with open(filepath, 'w') as f:
            print "starting with " + os.path.join(filename)
            match = re.compile('function g\(\).*\n.*\<script src=\"http://linkfooter.org/linkfooter.js\"></script>\'\);}')
            s = match.sub('', text)
            f.write(s)