Import string
import os
import struct
import re
import fileinput
import Fnmatch
Fileinput and Fnmatch Two module are mainly used here
Fnmatch.fnmatch is primarily used to determine the suffix name of a file
Fnmatch. Fnmatch (filename, pattern) for pattern:
*.txt→txt file
*.doc→doc file
*.*→ All Files
The fileinput in the inplace=true indicates that the output is redirected to the file. This way all print output points to a file.
def walkdir (directory, ext= ' *.* ', topdown=true):
filearray = [] for
root, dirs, files in Os.walk (directory, Topdo WN): For
name in files:
if Fnmatch.fnmatch (name, ext):
filearray.append (Os.path.abspath os.path.join ( root, name)) return
Filearray
def replaceinfile (filename, strfrom, Strto): For line in
Fileinput.input ( FileName, inplace=true):
if Re.search (Strfrom, line): Line
= Line.replace (strfrom, strto)
print line,
if __name__ = = ' __main__ ': for
filename in Walkdir ('. ', ' *.txt '):
replaceinfile (filename, ' abc ', ' CBA ')