import os, fnmatch
def findReplace(directory, find, replace, filePattern):
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
enc='utf-8'
with open(filepath,"r",encoding=enc) as f:
s = f.read()
try:
s = s.encode("iso-8859-1").decode("utf-8")
except (UnicodeEncodeError, UnicodeDecodeError):
pass
s = s.replace(find, replace)
with open(filepath, "w",encoding='utf-8', errors='ignore' ) as f:
f.write(s)
def main():
mylist = [ ("findstring", "replacestring")]
for item in mylist:
findReplace('.', item[0], item[1], '*.*')
if __name__=="__main__":
main()
我正在尝试搜索并替换给定文件夹内所有文件中的字符串。 Folder有各种文件及其窗口服务器。 我正在使用python 3.0。如何避免Unicodedecode错误?