[python] 파일에서 특정 문자열 치환하기
파일 읽기 및 문자열 치환
file_path = 'file.txt'
search_string = 'old_string'
replace_string = 'new_string'
with open(file_path, 'r') as file:
file_contents = file.read()
modified_contents = file_contents.replace(search_string, replace_string)
위의 코드에서는 파일을 열어서 해당 파일의 내용을 문자열로 읽어들인 다음, replace()
함수를 사용하여 특정 문자열을 다른 문자열로 치환했습니다. 이제 modified_contents
에는 치환된 내용이 담겨 있을 것입니다.
파일에 수정된 내용 쓰기
with open(file_path, 'w') as file:
file.write(modified_contents)
이제 w
모드를 사용하여 파일을 열어서 수정된 내용을 파일로 다시 씁니다.
완성된 코드
file_path = 'file.txt'
search_string = 'old_string'
replace_string = 'new_string'
with open(file_path, 'r') as file:
file_contents = file.read()
modified_contents = file_contents.replace(search_string, replace_string)
with open(file_path, 'w') as file:
file.write(modified_contents)
위의 코드를 사용하면 특정 파일에서 원하는 문자열을 치환할 수 있습니다. 필요하다면 파일 열기 및 닫기에 관한 예외처리도 추가할 수 있습니다.