Python
Python replace in file
idkbj
2014. 12. 2. 16:16
아래는 파일내 특정문자열을 변경하는 프로그램이다.
단 10분만에 작성한 프로그램인데, 이걸 자바로 하려면 꽤 번거롭다. file inputstream, outputstream 작성해야 하고.. file 목록 뽑아야 하고 등등..
이런 작업은 python의 생산성이 월등히 높다. java와 python 을 같이 사용한다면 매우좋을듯..
from os import listdir from os.path import isfile, join import codecs def replaceInFile(file_path, old, newstr): f = codecs.open(file_path, 'r', encoding='utf8') read_file = f.read() f.close() new_file = codecs.open(file_path,'w', encoding='utf8') for line in read_file.split("\n"): new_file.write(line.replace(old, newstr)) new_file.write("\n") #close file new_file.close() mypath = "D:/was/apache-tomcat-7.0.47-windows-x64/apache-tomcat-7.0.47/webapps/bong" onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ] for fname in onlyfiles: fpath = join(mypath,fname) print fpath replaceInFile(fpath, "old", "new");