Daily Archives: Salı, Kasım 29, 2011

  • Python ile dosya replace

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

    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)