recursive file editing

TaeKyon mikalzetTogli at interfree.it
Wed Apr 7 18:45:15 EDT 2004


Il Wed, 07 Apr 2004 23:04:51 +0200, Peter Otten ha scritto:

> # using your variable names
> for folders, folder, filelist in os.walk(target_folder):
>     os.chdir(folders)
>     for line in fileinput.input(filelist, inplace=1):
>         print re.sub(original_pattern,result_pattern,line),

I thought it might not work on files contained in subdirectories
but it does. The comma solved the problem with newlines too.

If we leave out the exception checking that's 5 lines of code:

import os, sys, re, fileinput
targetf, original, result = (sys.argv[1]), (sys.argv[2]), (sys.argv[3]) 
for folders, folder, filelist in os.walk(targetf):
    os.chdir(folders)
    for line in fileinput.input(filelist,inplace=1):
        print re.sub(original,result,line),

Compact and elegant !
Tomorrow I'll go about adding the change filename stuff.

--  
Michele Alzetta




More information about the Python-list mailing list