다음 코드는 폴더의 파일을 반복하고 간단한 검색 및 바꾸기를 수행 한 다음 결과를 다른 폴더로 출력합니다. 내가 아는 것은 교체 문자열이 두 번 적용되는 것 같습니다. 예를 들어파이썬 검색 및 바꾸기가 문자열 바꾸기를 복제합니까?
:
Search string: foo
Replace string: foo bar
Result: foo bar bar
여기 내 코드입니다. 나는 그 문제가 명백하다고 확신하지만, 나는 단지 그것에 손가락을 넣을 수 없다.
def SearchReplace(directory, search, 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)
outfile = os.path.join(outputdir, filename)
with open(filepath) as f:
s = f.read()
s = s.replace(search, replace)
with open(outfile, "w") as f:
f.write(s)
SearchReplace(inputdir, searchstr, replacestr, ext)
참고 : 결과를 별도의 폴더로 출력하지 않으면 검색/바꾸기가 예상대로 수행됩니다. 의미, 아래 코드는 잘 작동합니다 (같은 폴더에있는 입력 파일을 수정) :
def SearchReplace(directory, search, 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)
with open(filepath) as f:
s = f.read()
s = s.replace(search, replace)
with open(filepath, "w") as f:
f.write(s)
SearchReplace(inputdir, searchstr, replacestr, ext)
그러나 결과를 별도의 폴더에 출력해야합니다.
음, 원본 텍스트는 무엇입니까? 처음에 'foo bar'였다면 ... – cha0site