본문 바로가기
파이썬 언어

폴더의 모든 파일의 문자열을 replace 하기

by treeCoder 2021. 9. 9.

아래의 예는 html 내부에서, test2라는 문자열을 찾아서 test3라는 문자열로 변경하는 것이다.

결과는 output 이라는 폴더에 저장이 된다. 사용자가 원하는 이름으로 변경할 수 있다.

'''
https://stackoverflow.com/questions/50037369/find-and-replace-string-from-multiple-files-in-a-folder-using-python
'''

import glob
import ntpath
import os

output_dir = "output"

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

for f in glob.glob("*.html"):
    with open(f, 'r') as inputfile:
        with open('%s/%s' % (output_dir, ntpath.basename(f)), 'w') as outputfile:
            for line in inputfile:
                outputfile.write(line.replace('test2', 'test3'))

for f in glob.glob("*.html"): 에서 html을 txt 파일로 변경한다면, 모든 txt 파일에 대해서 작업이 된다.

 

댓글