Python ile dosya replace

Kasım 29, 2011 by · Leave a Comment 

php dosylarındaki mysql server ip adresini değiştirmek için kullanmıştım.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import fileinput, string, sys,os
Maindir = "/var/vhost"
OldIP = "123123"
NewIP = "345345"
LogFilePath = "test.log"
def replacemachine(fileName):
    ##################################################################
    file = open(fileName, "r") #Opens the file in read-mode
    text = file.read() #Reads the file and assigns the value to a variable
    file.close() #Closes the file (read session)
    file = open(fileName, "w") #Opens the file again, this time in write-mode
    file.write(text.replace(OldIP, NewIP)) #replaces all instances of our keyword
    # and writes the whole output when done, wiping over the old contents of the file
    file.close() #Closes the file (write session)
    logactions(fileName)
    ##################################################################
def listdir(ParentPath):    
    for f in os.listdir(ParentPath):
        if os.path.isfile(os.path.join(ParentPath,f)):
            if f.rfind(".php") > 0:
                print("file being replaced:",os.path.join(ParentPath,f))
                replacemachine(os.path.join(ParentPath,f))
                print("file replaced:",os.path.join(ParentPath,f))
        else:
            #print("directory:",f)
            listdir(os.path.join(ParentPath,f))
def logactions(FileName):
    LogStr = FileName + " replace edildi\n"
    LogFile = open(LogFilePath,"a")
    LogFile.write(LogStr)
if __name__ == "__main__":
    listdir(Maindir)