recursive file editing

TaeKyon mikalzetTogli at interfree.it
Wed Apr 7 15:49:31 EDT 2004


Il Tue, 06 Apr 2004 15:08:37 +0200, Peter Otten ha scritto:

> I suggest that you stick with with the simpler approach in my later post
> until you have a firm grip of classes. For the task at hand the Path class
> seems overkill, now I'm reconsidering it.

Here is a variation on the theme I came up with this afternoon:

#!/usr/bin/python
import os, sys, re, fileinput

try:
    target_folder = (sys.argv[1])
    original_pattern = (sys.argv[2])
    result_pattern = (sys.argv[3])
except:
    print "Substitutes a string with another in all files of a directory"
    print "		Use: ./MyScript.py directory string other_string"
    sys.exit()
for folders, folder, filelist in os.walk(target_folder):
    for filename in filelist:
        file = os.path.join(folders,filename)
        for line in fileinput.input(file,'inplace=1'):
            line = re.sub(original_pattern,result_pattern,line)
            print line   
#  Commented out because apparently useless, from the documentation I 
#  don't quite understand whether it ought to be here or not
#        fileinput.close()

This works - almost. 
1) It does substitute the pattern, however it seems to
add a newline for each newline present in the original file every time 
it is run (so files get longer and longer), and I don't understand why.
2) The final fileinput.close() seems to be useless; the program works
without, and bug 1) isn't affected.

--  
Michele Alzetta




More information about the Python-list mailing list